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
答案 0 :(得分:5)
嗯,首先:
yyy yobj = new xxx();
yobj.function1();
会导致编译错误。 yyy
是xxx
,但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();
将无法编译