Why would one create a Base Class object with reference to the Derived Class

后端 未结 3 1175
不思量自难忘°
不思量自难忘° 2021-02-06 03:56

I was practicing inheritance, using a test program in C# and I found out that the following statement does not throw an error:

BaseClass baseObj = new DerivedCla         


        
3条回答
  •  有刺的猬
    2021-02-06 04:49

    First off, the question why it's allowed, is simply because an instance of the derived class is an instance of the base class (subtype polymorphism). Same goes for being able to assign any derived class to an object variable: all .net classes derive from object in the end, so you could also have done object baseObj = new DerivedClass().

    The goal of the type that is used for the declaration is to indicate which type of interface is being worked with (intent). If you would declare the variable as object, you'd say that only the reference is important. If you declare as BaseClass, you say that you are using an object where the properties and methods of BaseClass are important. By using BaseClass baseObj = new DerivedClass(), you are saying you need the BaseClass functionality, but are using a DerivedClass instance to define the workings of the mapping described in BaseClass.

    One reason for this could be that BaseClass is abstract (BaseClasses often are), you want a BaseClass and need a derived type to initiate an instance and the choice of which derived type should be meaningful to the type of implementation.

    A reason for which it's even more often used, is because at any time, another class deriving from BaseClass can be assigned to the same variable. Consider:

    BaseClass baseObj = SomeCriterium ? (BaseClass)new DerivedClass() : new AlternateDerivedClass(); 
    

    The scope of the variable in the example is only in the main method, but if it were anywhere in the class, or it could be changed through a property or otherwise, by using BaseClass, anyone using your class could assign other BaseClass (derived) instance, instead of only DerivedClass (derived) instances.

    Finally an example for reassigning, using an interface declaration (as far as polymorphism is concerned, the same can be applied to declaring an implemented interface instead of the class as it can to a baseclass):

    IEnumerable values = new List();
    if(needfilter)
        values = values.Where(el => filtercriterium);
    

    If values was declared as a List, the values variable could not be reused for the filtered enumeration. Basically first you say that you need the values variable only for enumeration. After that you can reassign values with another enumeration instead of only with a list.

提交回复
热议问题