本文介绍了铸造填充的列表<&的BaseClass GT;列出< ChildClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表与LT; BaseClass的> 在它的成员。我想名单(及其所有成员特别是)转换为类型列表< ChildClass> ,其中 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();

这篇关于铸造填充的列表&LT;&的BaseClass GT;列出&LT; ChildClass&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 15:45