C#,如何在泛型方法中访问对象方法

C#, How to access object methods in a generic method

我有 2 个数据 类 有一个方法 isSenior()。

public class Staff : Member, IComparable<Staff>, IEquatable<Staff>
{
    public string Occupation { get; set; }
    public override bool isSenior()
    {
        var today = DateTime.Today;
        var age = today.Year - Birthday.Year;

        if (age > 65)
        {
            return true;
        }
        return false;
    }
}

public class Player : Member, IComparable<Player>, IEquatable<Player>
{
    public double Height { get; set; }
    public string Position { get; set; }
    public string Club { get; set; }
    public bool Invited { get; set; }
    public bool Captain { get; set; }
    public override bool isSenior()
    {
        var today = DateTime.Today;
        var age = today.Year - Birthday.Year;

        if (age > 30)
        {
            return true;
        }
        return false;
    }
}

我想在另一个通用方法中使用此方法,例如returns所有高级人员的列表

List<Player> allSeniorPlayers = TaskUtils.findSeniorMembers<Player>(allPlayers)

是否可以像这样调用 isSenior() 方法:

    public List<T> findSeniorMembers<T>(List<T> allMembers)
    {
        List<T> seniorMembers = new List<T>();
        foreach (T member in allMembers)
        {
            if(member.isSenior())
            {
                seniorMembers.Add(member);
            }
        }
        return seniorMembers;
    }

错误在 member.isSenior() 上。有什么办法可以做到这一点吗?

如果在Member中定义了isSenior,你只需要将T限制为Member或其子类型:

public List<T> findSeniorMembers<T>(List<T> allMembers) where T : Member

文档: