将派生类的列表转换为仍返回派生类的对象的基类列表 [英] Casting List of derived class to List of base class still returning objects of derived class
问题描述
我有以下代码:
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();
代码编译没有任何错误,但是,我希望 _baseClass
仅包含属性 A
(类型为 BaseClass
的对象),但它都返回 A
和 B
属性(类型为 DerivedClass
的对象)。我缺少什么?将派生类列表转换为基类列表的正确方法是什么?
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?
谢谢。
推荐答案
我缺少什么?将派生类列表转换为基类列表的正确方法是什么?
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?
列表仍然包含 DerivedClass
的实例,但它们正在被使用作为对 BaseClass
的引用。
The list still contains instances of the DerivedClass
, but they are being used as references to the BaseClass
.
该API的任何使用者都不知道这一点,因此他们会看到这是 BaseClass
元素。
Any consumer of this API will not know this, however, so they would see this as BaseClass
elements.
这很常见,通常是正确的方法。如果您需要将实例实际转换到 BaseClass
实例(可能没有必要),则需要实际制作新的<$ c $ DerivedClass
成员中的c> BaseClass 实例,即:
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();
通常这不是必需的,并且您当前的方法可能很好。 Liskov替换原则指出,任何 DerivedClass
应该在任何 BaseClass
的情况,这意味着只返回列表即可。
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.
这篇关于将派生类的列表转换为仍返回派生类的对象的基类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!