简体   繁体   English

C#中的动态绑定

[英]Dynamic Binding in C#

class A 
 {
   public virtual void WhoAreYou() { Console.WriteLine("I am an A"); }
 }
class B : A
{
  public override void WhoAreYou() { Console.WriteLine("I am a B"); }
}
class C : B
{
 public new virtual void WhoAreYou() { Console.WriteLine("I am a C"); }
}
class D : C 
{
  public override void WhoAreYou() { Console.WriteLine("I am a D"); }
}


C c = new D();
c.WhoAreYou();// "I am a D"
A a = new D();
a.WhoAreYou();// "I am a B" !!!!

How the reference is allocated internally, reference A contains the reference of B? 如何在内部分配引用, 引用A包含B的引用? Can any one explain Whats going On? 谁能解释一下怎么回事?

In class C , the method WhoAreYou() doesn't override the base class method, as it is defined with new keyword which adds a new method with the same name which hides the base class method. 在类C ,方法WhoAreYou()不会覆盖基类方法,因为它是使用new关键字定义的, new关键字添加了一个隐藏基类方法的同名 方法。 That is why this: 这就是为什么:

C c = new D();
c.WhoAreYou();// "I am a D"

invokes the overridden method in D which overrides its base class method defined with new keyword. D调用重写的方法,该方法覆盖用new关键字定义的基类方法。

However, when the target type is A , then this: 但是,当目标类型为A ,则:

A a = new D();
a.WhoAreYou();// "I am a B" !!!!

invokes the overridden method in B , as you're calling the method on a of type A whose method is overriden by B . 在调用重写的方法B ,为你呼吁法a类的A ,其方法是通过重写B

Your class C WhoAreYou() method is 'new', and therefor hiding the one from B. That means that the override in class D is overriding C's method instead of B's (which is overriding A's). 你的C类WhoAreYou()方法是'new',因此隐藏了B中的那个。这意味着D类中的覆盖覆盖了C的方法而不是B的(覆盖了A的)。

Since you have a reference to an A, the furthest down the hierarchy of it's WhoAreYou() function is the one in class B. 由于你有一个A的引用,它的层次结构中最远的是WhoAreYou()函数是B类中的一个。

http://msdn.microsoft.com/en-us/library/435f1dw2.aspx http://msdn.microsoft.com/en-us/library/435f1dw2.aspx

It is mean, that the C's 这是C的意思

public new virtual void WhoAreYou(){}

breaks the chain of virtual methods. 打破了虚拟方法的链条。

When you call the method WhoAreYou() of D by reference of A. The virtuality starts work, but it breaks at C. 当您通过引用A调用D的方法WhoAreYou()时。虚拟性开始工作,但它在C处中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM