Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 向列表中添加新方法<;T>;在一个物体上,它是由_C#_Methods - Fatal编程技术网

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();

您可以编写一个扩展方法doAcreach
sector01.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();