我在以 OO 方式编码时遇到了一点问题。
这是我的代码:
public class BasicEngine
{
public string name = null;
public string id = null;
public BasicEngine()
{
name = "Name of basic engine type";
id = "Basic engine id here";
}
}
public class SuperEngine: BasicEngine
{
public string name = null;
public string address = null;
public SuperEngine()
{
name = "Name of super engine here";
address = "Super engine address here";
}
}
我通过以下方式制作这些类的对象:
BasicEngine e1 = new BasicEngine();
MessageBox.Show("e1 type is " + e1.GetType().ToString());
SuperEngine e2 = new SuperEngine();
MessageBox.Show("e2 is " + e2.GetType().ToString());
BasicEngine e3 = new SuperEngine();
MessageBox.Show("e3 is " + e3.GetType().ToString());
SuperEngine e4 =BasicEngine(); // error An explicit conversion exist (are you missing cast ?) and if I try to cast it like SuperEngine e4 =(SuperEngine ) new BasicEngine(); it give run time error.
e1 应该是 BasicEngine 。e2 应该是 SuperEngine。
以下是我的困惑和问题:
e3 是 BasicEngine 类型,它显示了它的数据,我希望它是 SuperEngine 类型,为什么会这样?
e4 给出错误:错误
An explicit conversion exist (are you missing cast ?)
,如果我尝试像SuperEngine e4 =(SuperEngine ) new BasicEngine();
它一样投射它会给出运行时错误。