有关 C# 中方法重写的问题
本文关键字:问题 重写 方法 有关 | 更新日期: 2023-09-27 17:55:30
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
}
普
首先:
yyy yobj = new xxx();
yobj.function1();
将导致编译错误。 yyy
是xxx
,但xxx
不是yyy
。
其次:
xxx xobj = new yyy();
xobj.function1();
将导致执行类 xxx
的function1()
,因为变量的类型为 xxx
。 要在类 yyy
上调用该方法,您需要将变量强制转换为类型 yyy
xxx xobj = new yyy();
((yyy)xobj).function1();
这是关于继承的经典常见误解。继承不是双向的。我的意思是子类是超类的一种类型..但反过来并非如此。
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
您不能将 xxx 转换为 yyy,因此yyy yobj = new xxx();
不会编译