Method overload resolution with regards to generics and IEnumerable

后端 未结 2 1320
无人及你
无人及你 2020-12-03 14:18

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

public void Print(IEnumerable items) {
    Console.WriteLine(\"IEnumerab         


        
2条回答
  •  暖寄归人
    2020-12-03 14:27

    Because the methods generated from the generics Print(Person[] item) and Print(List item) are a better match than IEnumerable.

    The compiler is generating those methods based on your type arguments, so the generic template Print(T item) will get compiled as Print(Person[] item) and Print(List item) (well, whatever type represents a List at compilation). Because of that, the method call will be resolved by the compiler as the specific method that accepts the direct type, not the implementation of Print(IEnumerable).

提交回复
热议问题