简体   繁体   English

在C#中基类引用指向派生对象更好还是派生类自己的对象更好

[英]In C# base class reference point to derived object is better or derived class own object is better

In the following example i have created three object i want to know what is the difference between three object , how it works and which to use and there is error in third object so , why it shows error?在下面的示例中,我创建了三个对象,我想知道三个对象之间有什么区别,它是如何工作的以及使用哪个对象,并且第三个对象中有错误,那么为什么它显示错误?

class Base
{

}
class Derived : Base
{

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

Inheritance is what you are doing in above code.继承是你在上面的代码中所做的。

Base base = new Derived() :

object of type Base class hold object of Derived class in which when you call method which are overridden in your Derived class, it'll call your derived class method.基类类型的对象保存派生类的对象,其中当您调用派生类中覆盖的方法时,它将调用派生类方法。 If the method is not overridden, it will call Base class method如果该方法未被覆盖,它将调用基类方法

Derived derived = new Derived() :

Derived class object holds object of Derived type in which you call method of it, it'll simply call Derived type method.派生类对象持有派生类型的对象,您在其中调用它的方法,它只会调用派生类型的方法。 It'll not check any overridden method.它不会检查任何重写的方法。

Derived derived_1 = new Base() :

This will not compile as child class can't hold object of base class.这不会编译,因为子类不能保存基类的对象。

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 )

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM