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

时间:2017-02-08 05:39:28

标签: c#

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

class Base
{

}
class Derived : Base
{

}
class Main
{
    Base base = new Derived();
    Derived derived = new Derived();
    Derived derived_1 = new Base(); 
}

2 个答案:

答案 0 :(得分:0)

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

Base base = new Derived() :

类型的对象基类类保持Derived类的对象,当您调用在Derived类中重写的方法时,它将调用派生类方法。如果未覆盖该方法,则将调用Base类方法

Derived derived = new Derived() :

派生类对象包含派生类型的对象,在其中调用它的方法,它只是调用派生类型方法。它不会检查任何被覆盖的方法。

Derived derived_1 = new Base() :

这不会编译,因为子类不能保存基类的对象。

答案 1 :(得分:0)

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