我认为被调用的方法是在运行时决定的,或者我错过了什么?示例代码:
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
。我可以做些什么来获取重载方法而不强制转换输入吗?
重载由编译器选择。对于此处的调用:
internal void DoStuff<T>(T input) where T : SomeBase
{
HiThere(input);
}
它选择具有SomeBase
,因为这就是它在编译时的全部内容。
您最可能想要的是覆盖。这意味着必须将不同的逻辑放入 SomeBase 的继承者中:
abstract class SomeBase
{
abstract string Name { get; }
}
class ImplA : SomeBase{ override string Name { get { return "ImplA"; } } }
class ImplB : SomeBase{ override string Name { get { return "ImplB"; } } }
void HiThere(SomeBase input)
{
Console.WriteLine(input.Name);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)