问题描述
我已经尝试了一些逻辑,但是我正在寻找一个更通用的解决方案,请帮助我解决其他问题。
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;
}
解决方法
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 result;
}
,
您可以自己使用泛型。这样,您曾经声明的方法将自动返回正确的类:
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,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
请参阅: