在C#基类中,引用点到派生对象更好,或者派生类自己的对象更好



在下面的例子中,我创建了三个对象,我想知道这三个对象之间的区别是什么,它是如何工作的,使用哪个,第三个对象中有错误,为什么会显示错误?

class Base
{
}
class Derived : Base
{
}
class Main
{
Base base = new Derived();
Derived derived = new Derived();
Derived derived_1 = new Base(); 
}
Base base = new Derived();//Here you are referencing the derived object with base reference type, so only base members will be accessed using the base reference  
Derived derived = new Derived();//Here you can access members in base and derived
Derived derived_1 = new Base();//This is a syntax error because you are using a derived reference for the base object(you are referencing a general object with a specific reference you need conversion here )

检查此链接:https://msdn.microsoft.com/en-us/library/ms173149.aspx

继承就是您在上面代码中所做的。

Base base = new Derived() :

基类类型的对象持有派生类的对象,当您在其中调用在派生类中重写的方法时,它将调用派生类方法。如果该方法未被重写,它将调用基类方法

Derived derived = new Derived() :

派生类对象包含派生类型的对象,您在其中调用它的方法,它将简单地调用派生类型的方法。它不会检查任何重写的方法。

Derived derived_1 = new Base() :

这将不会编译,因为子类不能容纳基类的对象。

相关内容

  • 没有找到相关文章

最新更新