【问题标题】:C# generic method for returning maxId用于返回 maxId 的 C# 泛型方法
【发布时间】:2018-05-23 15:30:34
【问题描述】:

我想有一个方法可以在我拥有的其他对象(例如:奖品、人员、团队等)上执行此代码,因此我不必多次编写相同的代码,只需假设 GetMaxId(List 个人,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;
    }

所以,我想要的是在每个类中,例如,我想在创建一个新人时返回该人的 id,但我不想修改代码以获取 Prize 的参数并拥有将其更改为人员。 我想要一个采用通用参数的方法,所以当我在 Person 类中调用它时,我可以只传递(列表人员,Person person)。

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

【问题讨论】:

  • 您使用哪种编程语言?你必须给我们更多的细节。你想让函数作为参数不同的对象吗?你想让所有的类都有这样的方法吗?看看继承和接口。用这么少的信息是不可能给出答案的。
  • @FrancescoBoi 很抱歉没有足够的澄清。希望这能解释清楚。
  • 对不起,但我认为没有。而且您还没有告诉我们您使用的是哪种编程语言。
  • @FrancescoBoi 我认为它会在标题 C# 中可见。
  • 你是对的,但你也应该像现在一样放入标签,因为通常问题是用标签分类的。

标签: c# generic-list


【解决方案1】:

好吧,我认为您想要的是一个通用函数来检索集合的下一个 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
    }

【讨论】:

  • Tnx,这解决了我的问题。我不知道我可以为此使用 Func。非常感谢:)
【解决方案2】:

这是一个使用接口的简单示例,您的所有东西都将实现这个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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多