Which C# method overload is chosen?

后端 未结 4 1517
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 01:23

Why is the generic method called when both overloads would match?

public static void method1(object obj)
{
    Console.WriteLine(\"Object\");
}

public stati         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 02:05

    Because you are already passing in T as a parameter so you don't need to type out method1("xyz");you can just go method1("xyz");, .Net already knows it's a string. If you had method1 then it would be a different story.

    Also since method1(object obj) doesn't take in a string as parameter it will favor the generic function first where it can infer T. If you were to change method1(object obj) to method1(string obj) it would favor it first then the generic.

提交回复
热议问题