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

落花浮王杯 提交于 2019-12-05 17:44:40

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.

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