本文介绍了C#中的数据绑定概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A级

{

public virtual void WhoAreYou(){Console.WriteLine(我是A); }

}

B级:A

{

公共覆盖无效WhoAreYou(){Console.WriteLine( 我是B); }

}

class C:B

{

public new virtual void WhoAreYou(){Console.WriteLine (我是C); }

}

D类:C

{

公共覆盖无效WhoAreYou(){Console.WriteLine( 我是D); }

}





C c = new D();

c.WhoAreYou(); //我是D

A a =新D();

a.WhoAreYou(); //我是一个B!!!!

任何人都可以解释一下怎么回事?

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" !!!!
Can any one explain Whats going On?

推荐答案

"WhoAreYou"-slot 1: A.WhoAreYou —> B.WhoAreYou
"WhoAreYou"-slot 2: C.WhoAreYou —> D.WhoAreYou





他们是无关的,只有相同的名字。发生这种情况是因为在 C 中你没有覆盖slot1-WhoAreYou 并带有覆盖,但重新引入同名的全新方法,同样是虚拟方法。这两个名称针对两个不同的无关插槽 互相隐藏 。如果您的编译时声明是 A B ,则隐含插槽1,如果 C D - 插槽2.



第二种情况,slot1-WhoAreYou 为您提供 A.WhoAreYou 的最新重写版本,该版本由 B定义。 WhoAreYou ,因此我是B。



作为一名有意识的开发人员,您需要了解虚拟方法的工作原理。换句话说,永远记住你是谁。 :-)



这有助于理解OOP级别的内容:

[],

[]。



-SA



They are unrelated, only have the same name. This happened because in C you did not override "slot1"-WhoAreYou with "override", but reintroduced a totally new method under the same name, again, a virtual one. These two names addressing two different unrelated slots hide each other. If your compile-time declaration is A or B, slot 1 is implied, if C or D — slot 2.

In second case, "slot1"-WhoAreYou gives you the latest overridden version of A.WhoAreYou, which was defined by B.WhoAreYou, hence "I am a B".

You need to learn how virtual methods work very deeply, as a conscious developer. In other words, always remember who are you. :-)

This can help to understand things on the OOP level:
http://en.wikipedia.org/wiki/Dynamic_dispatch[^],
http://en.wikipedia.org/wiki/Virtual_table[^].

—SA


这篇关于C#中的数据绑定概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:58