所以我在玩 C#,看看它是否与这篇文章中的 C++ 行为相匹配:http: //herbsutter.com/2013/05/22/gotw-5-solution-overriding-virtual-functions/ 当我遇到这个非常奇怪的行为:
public class BaseClass
{
public virtual void Foo(int i)
{
Console.WriteLine("Called Foo(int): " + i);
}
public void Foo(string i)
{
Console.WriteLine("Called Foo(string): " + i);
}
}
public class DerivedClass : BaseClass
{
public void Foo(double i)
{
Console.WriteLine("Called Foo(double): " + i);
}
}
public class OverriddenDerivedClass : BaseClass
{
public override void Foo(int i)
{
base.Foo(i);
}
public void Foo(double i)
{
Console.WriteLine("Called Foo(double): " + i);
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass derived = new DerivedClass();
OverriddenDerivedClass overridedDerived = new OverriddenDerivedClass();
int i = 1;
double d = 2.0;
string s = "hi";
derived.Foo(i);
derived.Foo(d);
derived.Foo(s);
overridedDerived.Foo(i);
overridedDerived.Foo(d);
overridedDerived.Foo(s);
}
}
输出
Called Foo(double): 1
Called Foo(double): 2
Called Foo(string): hi
Called Foo(double): 1
Called Foo(double): 2
Called Foo(string): hi
因此,显然它有利于隐式转换的 int 比基类中更具体的 Foo(int) 翻倍。或者它是否从基类中隐藏了 Foo(int) ?但是然后:为什么 Foo(string) 不隐藏?感觉很不一致......我是否覆盖 Foo(int) 也没关系;结果是一样的。谁能解释这里发生了什么?
(是的,我知道在派生类中重载基方法是不好的做法——Liskov 等等——但我仍然不希望 OverriddenDerivedClass 中的 Foo(int) 不被调用?!)