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
}
Run Code Online (Sandbox Code Playgroud)
PLE
好吧,首先:
yyy yobj = new xxx();
yobj.function1();
Run Code Online (Sandbox Code Playgroud)
将导致编译错误. yyy是一个xxx,但xxx不是一个yyy.
其次:
xxx xobj = new yyy();
xobj.function1();
Run Code Online (Sandbox Code Playgroud)
将导致function1()类xxx被执行,因为变量是类型xxx.要在类上调用该方法,yyy您需要将变量强制转换为类型yyy
xxx xobj = new yyy();
((yyy)xobj).function1();
Run Code Online (Sandbox Code Playgroud)