我認爲被調用的方法是運行時決定的,還是我錯過了某些東西?示例代碼:爲什麼重載的方法不被調用?
class Program
{
static void Main(string[] args)
{
var magic = new MagicClass();
magic.DoStuff(new ImplA());
magic.DoStuff(new ImplB());
Console.ReadLine();
}
}
class MagicClass
{
internal void DoStuff<T>(T input) where T : SomeBase
{
HiThere(input);
}
void HiThere(SomeBase input)
{
Console.WriteLine("Base impl");
}
void HiThere(ImplA input)
{
Console.WriteLine("ImplA");
}
void HiThere(ImplB input)
{
Console.WriteLine("ImplB");
}
}
abstract class SomeBase
{
}
class ImplA : SomeBase{}
class ImplB : SomeBase{}
我想我會得到:
ImplA
ImplB
作爲輸出,但它打印Base impl
。有沒有什麼我可以做,而不是投入輸入重載的方法?
這是一個相當不錯的解釋爲什麼:http://csharpindepth.com/Articles/General/Overloading.aspx –