C# 向列表中添加新方法<;T>;在一个物体上,它是由
是否有方法将新方法添加到列表对象中,并覆盖由其组成的对象。换句话说,类可以这样编写,当列表由它组成时,它会将新方法添加到该列表中。下面是一个例子:C# 向列表中添加新方法<;T>;在一个物体上,它是由,c#,methods,C#,Methods,是否有方法将新方法添加到列表对象中,并覆盖由其组成的对象。换句话说,类可以这样编写,当列表由它组成时,它会将新方法添加到该列表中。下面是一个例子: class Employee { public int age; public Employee(int age) { this.age = age; } //some more code here... } 然后: List<Employee> sector01 = new L
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
List sector01=newlist(){新员工(22),新员工(35)};
sector01.OutputAll()//添加这样的方法
您可以将其定义为:
现在您将能够做到这一点:
List<Employee> sector01 = new List<Employee>()
{
new Employee(22),
new Employee(35)
};
sector01.OutputAll();
List sector01=新列表()
{
新雇员(22人),
新雇员(35)
};
sector01.OutputAll();
您可以编写一个扩展方法doAcreachsector01.OutputAll()代码>
静态类EmployeeListensions
{
公共静态void OutputAll(此IEnumerable employeeList)
{
...
}
}
您所说的是一个。你可以用英文写
您必须编写一个静态类来包含扩展方法,尽管它们不必都在同一个类中。然后可以像在初始类定义中一样使用它们
像这样:
public static class ListExtensions
{
public static void OutputAll<T>(this List<T> list)
{
//do something
}
}
如您所见,调用OutputAll
的代码与您预期的一样
List<Employee> sector01 = new List<Employee>()
{
new Employee(22),
new Employee(35)
};
sector01.OutputAll();
static class EmployeeListExtensions
{
public static void OutputAll(this IEnumerable<Employee> employeeList)
{
...
}
}
public static class ListExtensions
{
public static void OutputAll<T>(this List<T> list)
{
//do something
}
}
List<Employee> sector01 = new List<Employee>(){new Employee(22), new Employee(35)};
sector01.OutputAll();