gpt4 book ai didi

c# - 在由以下内容组成的对象上向 List 添加新方法

转载 作者:行者123 更新时间:2023-11-30 13:33:40 25 4
gpt4 key购买 nike

有没有办法在 List 对象的基础上向 List 对象添加新方法。换句话说,类是否可以这样编写,当 List 由它构成时,它会向该 List 添加新方法。这是一个例子:

class Employee
{
public int age;
public Employee(int age)
{
this.age = age;
}
//some more code here...
}

然后:

List<Employee> sector01 = new List<Employee>(){new Employee(22), new Employee(35)};
sector01.OutputAll(); //Adds method like this

最佳答案

您可以将其定义为 extension method :

namespace SomeNamespace
{
public static class ListExtensions
{
public static void OutputAll(this IEnumerable<Employee> employees)
{
foreach (var employee in employees)
{
Console.WriteLine("{0}: {1}", employee.FirstName, employee.LastName);
}
}
}
}

然后简单地将定义这个静态类的命名空间引入作用域:

using SomeNamespace;

现在您将能够做到这一点:

List<Employee> sector01 = new List<Employee>()
{
new Employee(22),
new Employee(35)
};
sector01.OutputAll();

关于c# - 在由以下内容组成的对象上向 List<T> 添加新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6412288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com