为什么不调用重载方法? [英] Why isn't the overloaded method getting called?
本文介绍了为什么不调用重载方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为正在调用的方法是确定的运行时,还是我错过了什么?示例代码:
I thought the method that is getting called is decided runtime, or have I missed something? Sample code:
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
.在不强制转换输入的情况下,我能做些什么来获取重载方法吗?
as output but it prints Base impl
. Is there anything I can do to get the overloaded method without casting the input?
推荐答案
重载由编译器选择.对于此处的通话:
Overloads are chosen by the compiler. For the call here:
internal void DoStuff<T>(T input) where T : SomeBase
{
HiThere(input);
}
它选择带有 SomeBase
的代码,因为这就是编译时的全部内容.
it chooses the one with SomeBase
, because that's all it has at compile time.
您最可能想要的是覆盖.这意味着必须将不同的逻辑放入SomeBase的继承者中:
What you most probably want is overrides. This means that the different logic has to be put into the inheritors of 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);
}
这篇关于为什么不调用重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文