我有一个返回的方法List<ThisInterface>
。我希望List<ThisClass>
只要ThisClass实现ThisInterface ,就可以将该方法的结果转换为。但是,我尝试执行此操作时收到以下错误消息:
无法将类型的对象转换
System.Collections.Generic.List'1[IThisInterface]
为类型System.Collections.Generic.List’1[ThisClass]
。
有什么想法吗?我需要为此编写一个构造函数吗?
如果您有个List<IThisInterface>
,则无法将该列表对象强制转换为List<ThisClass>
。即使列表中的所有项目都是ThisClass
对象,该列表仍然是IThisInterface
对象列表。
你需要做的是建立一个新的List<ThisClass>
列表,然后填充与原始列表的所有项目,但投那些到ThisClass
第一。
幸运的是,这正是LINQ方法的Enumerable.Cast<T>
作用:
List<IThisInterface> list = GetData();
// cast the list to a `ThisClass` list
List<ThisClass> newList = list.Cast<ThisClass>().ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句