相关疑难解决方法(0)

关于泛型和IEnumerable的方法重载决策

前几天我注意到这一点,说你有两个重载方法:

public void Print<T>(IEnumerable<T> items) {
    Console.WriteLine("IEnumerable T"); 
}
public void Print<T>(T item) {
    Console.WriteLine("Single T"); 
}
Run Code Online (Sandbox Code Playgroud)

这段代码:

public void TestMethod() {  
    var persons = new[] { 
        new Person { Name = "Yan", Age = 28 },
        new Person { Name = "Yinan", Age = 28 } 
    };  
    Print(persons);
    Print(persons.ToList()); 
}
Run Code Online (Sandbox Code Playgroud)

打印:

Single T
Single T
Run Code Online (Sandbox Code Playgroud)

在这些情况下,为什么Person[]和他们相比List<Person>更好?TIEnumerable<T>

谢谢,

更新: 此外,如果你有另一个重载

public void Print<T>(List<T> items) {
    Console.WriteLine("List T");
}
Run Code Online (Sandbox Code Playgroud)

Print(persons.ToList());实际上会打印List T而不是Single …

.net c# overloading overload-resolution

19
推荐指数
1
解决办法
1406
查看次数

标签 统计

.net ×1

c# ×1

overload-resolution ×1

overloading ×1