我试图弄清楚 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
执行中的代码时,Foo()
从基类 ( Animal
) 被调用,并且从我读到的关于阴影的内容中,应该调用Foo()
from 。Dog
有人可以解释我错过了什么吗?
我的例子是根据这个: 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()
从派生类被调用,在我的示例中不是这种情况。