阴影隐藏了基类中的方法。使用您链接的问题中的示例:class A { public int Foo(){ return 5;} public virtual int Bar(){return 5;}}class B : A{ public new int Foo() { return 1;} public override int Bar() {return 1;}}类B 重写虚拟方法Bar。它隐藏(遮盖了)非虚拟方法Foo。替代使用override关键字。阴影是通过new关键字完成的。在上面的代码中,如果在class中定义方法时未使用new关键字,则会收到以下编译器警告:FooB'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.
假设我有一个实现虚拟方法的基类:public class A{ public virtual void M() { Console.WriteLine("In A.M()."); }}我也有一个派生类,它也定义了方法M:public class B : A{ // could be either "new" or "override", "new" is default public void M() { Console.WriteLine("In B.M()."); }}现在,假设我编写了这样的程序:A alpha = new B(); // it's really a B but I cast it to an Aalpha.M();对于我希望如何实现,我有两种选择。默认行为是调用A的M版本。(这与将new”关键字应用到的行为相同B.M())。当从基类中调用具有相同名称但行为不同的方法时,这称为“阴影”。或者,我们可以在上指定“ override” B.M()。在这种情况下,alpha.M()本应称为B的M版本。