铸造填充的列表<&的BaseClass GT;列出< ChildClass>

铸造填充的列表<&的BaseClass GT;列出< ChildClass>

问题描述:

我有一个列表与LT; BaseClass的&GT; 在它的成员。我想名单(及其所有成员特别是)转换为类型列表&LT; ChildClass&GT; ,其中 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。如果这真的是你的意图,这将是等价的:

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();