关于c#中方法覆盖的问题

时间:2011-05-07 08:49:26

标签: c#

class xxx
{
   public virtual void function1()
   {
     // Some code here
   }
}

class  yyy : xxx
{
   public override void function1()
   {
    // some code here
   }
}

class result
{
   public result(){}

   // In the main i write as

   xxx xobj = new yyy();
   xobj.function1(); // by calling this function1 in yyy will invoked

   yyy yobj = new xxx();
   yobj.function1()     // which function will be called here
}

PLE

3 个答案:

答案 0 :(得分:5)

嗯,首先:

yyy yobj = new xxx();
yobj.function1();

会导致编译错误。 yyyxxx,但xxx不是yyy

其次:

xxx xobj = new yyy();
xobj.function1();

将导致function1()xxx被执行,因为该变量的类型为xxx。要调用类yyy上的方法,您需要将变量强制转换为yyy

类型
xxx xobj = new yyy();
((yyy)xobj).function1();

答案 1 :(得分:3)

这是关于继承的一个典型的常见误解。继承不是双向的。通过这个我的意思是一个子类是一个超类的类型..但反过来却不是这样。

public class Base
{
}

public class Sub : Base
{
}


Base baseObj = new Base(); //this is just fine
Base subAsBase = new Sub(); //this is just fine, a Sub is a type of Base

Sub subAsBase = new Base(); //this will spit a compile error. A Base is NOT a type of Sub, it is the other way around.

同样,我可以执行以下投射:

Base baseObj = null;
Sub subObj = new Sub();
baseObj = subObj; //now I am storing a sub instance object in a variable declared as Base

Sub castedSubObj = baseObj as Sub; //simply casted it back to it's concrete type

答案 2 :(得分:1)

您无法将xxx转换为yyy,因此yyy yobj = new xxx();将无法编译