您可以自己使用泛型。这样,您曾经声明的方法将自动返回正确的类:
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
看: