Method overload resolution with regards to generics and IEnumerable

I noticed this the other day, say you have two overloaded methods:

public void Print<T>(IEnumerable<T> items) {
    Console.WriteLine("IEnumerable T"); 
}
public void Print<T>(T item) {
    Console.WriteLine("Single T"); 
}

This code:

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

prints:

Single T
Single T

Why are Person[] and List better matched to T than they are to IEnumerable in these cases?

Thanks,

UPDATE: Also, if you have another overload

public void Print<T>(List<T> items) {
    Console.WriteLine("List T");
}

Print(persons.ToList()); will actually print List T instead of Single T.

19
задан theburningmonk 5 February 2011 в 22:27
поделиться