Casting List of derived class to List of base class still returning objects of derived class

北慕城南 提交于 2019-12-22 07:55:59

问题


I have the following code:

public class BaseClass
{
    public string A { get; set; }
}

public class DerivedClass : BaseClass
{
    public string B { get; set; }
}


List<DerivedClass> _derivedClass = new List<DerivedClass>() 
                                       { 
                                           new DerivedClass() 
                                             { A = "test1",
                                               B = "test2"
                                             }
                                       }; 

List<BaseClass> _baseClass = _derivedClass.Cast<BaseClass>.ToList();

The code compiles without any error, however, I expected _baseClass to only contain Property A (object of type BaseClass), but it's return both A and B properties (objects of type DerivedClass). What am I missing and what's the correct way to convert a List of a derived class to a list of its base class?

Thank you.


回答1:


What am I missing and what's the correct way to convert a List of a derived class to a list of its base class?

The list still contains instances of the DerivedClass, but they are being used as references to the BaseClass.

Any consumer of this API will not know this, however, so they would see this as BaseClass elements.

This is common, and typically the correct approach. If you needed to actually convert the instances to BaseClass instances (which is likely not necessary), you would need to actually make new BaseClass instances from the DerivedClass members, ie:

List<BaseClass> _baseClass = _derivedClass.Select(dc => new BaseClass {A = dc.A}).ToList();

That is typically not necessary, and your current approach is likely fine. The Liskov substitution principle states that any DerivedClass should be usable in any situation as a BaseClass, which means just returning the list as you did should be fine.



来源:https://stackoverflow.com/questions/14817306/casting-list-of-derived-class-to-list-of-base-class-still-returning-objects-of-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!