【发布时间】:2015-06-22 08:47:00
【问题描述】:
我试图弄清楚 c# 中阴影的概念。这是我的代码,它的行为与我预期的不同:
public class Animal
{
public virtual void Foo()
{
Console.WriteLine("Foo Animal");
}
}
public class Dog : Animal
{
public new void Foo()
{
Console.WriteLine("Foo Dog");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog1 = new Dog();
((Animal)dog1).Foo();
Animal dog2 = new Dog();
dog2.Foo();
}
}
当Main 中的代码被执行时,基类(Animal) 中的Foo() 被调用,从我读到的关于阴影的内容中,应该调用Dog 中的Foo()。有人可以解释我缺少什么吗?
我的例子是这样的: https://msdn.microsoft.com/en-us/library/ms173153.aspx
更新: 这是来自 msdn 的示例:
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
当执行bcdc.Method1() 时,派生类中的Method1() 会被调用,而在我的示例中并非如此。
【问题讨论】:
-
哪一点让您期望来自
Dog的Foo()方法会被调用?在这两种情况下,您都是通过编译时类型为Animal的表达式调用它。 -
Car/ConvertibleCar/Minivan准确显示了您正在尝试执行的操作。同一页。 -
重点是,如果你想让一个方法调用转到一个被覆盖的方法,你需要一个不间断的
virtual/override链。new中断了这条链。 -
这表明在大多数情况下,阴影/隐藏是邪恶化身的产物,本不应该出现:请参阅stackoverflow.com/questions/2663274/… 了解可以使用它的情况(以弥补另一个缺点)语言)