#c# #.net #list #object #generic-programming
#c# #.net #Список #объект #generic-программирование
Вопрос:
Я попробовал ниже некоторую логику, но я ищу более общее решение, пожалуйста, помогите мне, есть ли какой-либо другой способ получить объект.
static class FinObj
{
public static ppl Find(List<ppl> obj, string Name)
{
foreach (var item in obj)
{
if (item.Name == Name)
{
return (item);
}
}
return null;
}
}
static void Main(string[] args)
{
student d = FinObj.Find(stuList, "B") as student;
teacher x = FinObj.Find(patientList, "BB") as teacher;
}
Ответ №1:
public static dynamic Find(List<Person> obj, string Name)
{
var result = obj.Find(x => x.Name == Name);
if (result != null)
{
Console.WriteLine("ID:" result.ID ", Name:" result.Name ", Gender:" result.Gender);
}
Console.WriteLine("Not Found");
return resu<
}
Ответ №2:
Вы можете использовать дженерики самостоятельно. Таким образом, ваш однажды объявленный метод автоматически вернет правильный класс:
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public int ID { get; set; }
public string Name { get; set; }
public char Gender { get; set; }
public override string ToString() => $"{GetType()} {ID} {Name} {Gender}";
}
class Patient : Person { }
class Doctor : Person { }
static class FinderObject
{
// what you want to do can be done using Linq on a list with FirstOrDefault
// so there is no real use to create the method yourself if you could instead
// leverage linq
public static T Find<T>(List<T> data, string Name)
where T : Person
=> data.FirstOrDefault(p => p.Name == Name);
}
Использование:
public static class Program
{
static void Main(string[] args)
{
var docList = Enumerable.Range(1, 10)
.Select(n => new Doctor() { ID = n, Name = $"Name{n}", Gender = 'D' })
.ToList();
var patientList = Enumerable.Range(100, 110)
.Select(n => new Patient() { ID = n, Name = $"Name{n}", Gender = 'D' })
.ToList();
// finds a doctor by that name
Doctor d = FinderObject.Find(docList, "Name3");
// patient does not exist
Patient x = FinderObject.Find(patientList, "Name99");
Console.WriteLine($"Doc: {d}");
Console.WriteLine($"Pat: {(x != null ? x.ToString() : "No such patient")}");
Console.ReadLine();
}
}
Вывод:
Doc: Doctor 3 Name3 D
Pat: No such patient
См.:
Комментарии:
1. Большое спасибо за ваш ответ, я использовал ключевое слово dynamic в качестве возвращаемого типа, чтобы избежать типизации.