问题描述
我有一个 List
,里面有成员.我想将列表(特别是它的所有成员)转换为 List
类型,其中 ChildClass
继承 BaseClass
.我知道我可以通过 foreach 获得相同的结果:
I have a List<BaseClass>
with members in it. I would like to cast the list (and all its members specifically) to a type List<ChildClass>
, where ChildClass
inherits BaseClass
. I know I can get the same result through a foreach:
List<ChildClass> ChildClassList = new List<ChildClass>();
foreach( var item in BaseClassList )
{
ChildClassList.Add( item as ChildClass );
}
但是有没有更简洁的方法来做到这一点?注意 - 这是在 WP7 平台上完成的.
But is there a neater way of doing this? Note - this is done on the WP7 platform.
推荐答案
如果你真的确定所有项目都是可转换的,你可以这样做:
You can do this if you are really sure all items are castable:
ChildClassList = BaseClassList.Cast<ChildClass>().ToList();
如果 BaseClass 项无法转换为 ChildClass,您当前的代码会添加 null
.如果这真的是您的意图,那么这将是等效的:
Your current code adds null
if a BaseClass item cannot be cast to ChildClass. If that was really your intention, this would be equivalent:
ChildClassList = BaseClassList.Select(x => x as ChildClass).ToList();
但我更愿意建议这样做,其中包括类型检查并会跳过不匹配的项目:
But i'd rather suggest this, which includes type checking and will skip items that don't match:
ChildClassList = BaseClassList.OfType<ChildClass>().ToList();
这篇关于铸造填充的 List<BaseClass>到列表<ChildClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!