我想有一个方法可以在我拥有的其他对象上执行此代码(例如:奖品,人员,团队等等),所以我不必多次编写相同的代码然后让我们说GetMaxId(List< Person> person,Person person)。 我的每个对象都有一个Id属性。 我正在使用这个,所以当我通过winform应用程序中的用户输入保存到文本文件时,所以我可以根据文本文件中当前人数(例如人数)生成大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;
}
所以,我想要的是每个类,例如我想在创建一个新人时返回该人的id,但我不想修改代码以获取参数奖并且必须将其更改为Person。 我想要一个采用泛型参数的方法,所以当我在Person类中调用它时,我只能传递(list person,Person person)。
我不知道在原始方法中传递哪种类型,以便我可以在其他类中重复使用它。
答案 0 :(得分:0)
这是一个使用接口的简单示例,其中所有内容都将实现此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));
}
答案 1 :(得分:0)
好吧,我认为你想要的是一个通用函数来检索集合的下一个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
}