返回 maxId 的 C# 泛型方法

C# generic method for returning maxId

我希望有一个方法可以在我拥有的其他对象(例如:奖品、个人、团队等)上执行此代码,这样我就不必多次编写相同的代码并让我们说 GetMaxId(List< Person > persons, Person person)。 我的每个对象都有一个 Id 属性。 我正在使用它,所以当我通过我的 winform 应用程序中的用户输入保存到文本文件时,我可以根据文本文件中的当前人数生成比 Persons 大 1 的 id。

public static int GetMaxId(List<Prize> prizes, Prize prize)
    {
        int maxId = 1;
        if (prizes.Count > 0)
            maxId = prizes.Max(p => p.Id) + 1;

        prize.Id = maxId;
        return prize.Id;
    }

所以,我想要的是每个 classes,例如我想 return 创建新人时的人的 ID,但我不想修改代码,使其不接受 Prize 的参数并将其更改为 Person。 我想要一个采用通用参数的方法,所以当我在 Person class 中调用它时,我可以只传递 (list persons, Person person).

我不知道在原始方法中传递哪种类型,以便我可以在其他 classes 中重用它。

这是一个使用接口的简单示例,您所有的东西都将实现此 IHaveId 接口以确保它们具有此 ID 属性。 getMaxId 函数是通用的,只需要您的列表是具有实现 IHaveId 接口的 id 属性的事物列表。

您可以在 https://dotnetfiddle.net/pnX7Ph 看到这个工作。

public interface IHaveId {
    int id { get; }
}

public class Thing1 : IHaveId {
    private int _id;
    public Thing1(int id) {
        this._id = id;
    }
    int IHaveId.id {
        get { return this._id; }
    }
}

public class Thing2 : IHaveId {
    private int _id;
    public Thing2(int id) {
        this._id = id;
    }
    int IHaveId.id {
        get { return this._id; }
    }
}   


public static int getMaxId<T>(List<T> list) where T : IHaveId {
    return list.Max(i => i.id);
}


public static void Main()
{
    List<IHaveId> things = new List<IHaveId>();
    for (var i=0; i<5; i++) {
        things.Add(new Thing1(i));
    }
    for (var i=10; i<15; i++) {
        things.Add(new Thing2(i));
    }

    Console.WriteLine("Max id is " + getMaxId(things));
}

好吧,我想你想要的是一个通用函数来检索集合的下一个 ID。您可以尝试使用泛型。

像这样:

public static int GetNextId<T>(List<T> items, Func<T,int> selector)
    {
        if (items.Count < 1)
            return 1;

        return items.Max(selector)+1;
    }

然后你像这样使用函数:

public class Person
    {
        public int PersonID { get; set; }
    }

    public static void Test()
    {
        var persons = new List<Person>()
        {
            new Person() {PersonID=1 },
            new Person() {PersonID=2 },

        };

        var nextId = GetNextId(persons, i => i.PersonID);//returns 3
    }