从List< X>转换的较短语法到列表< Y> ;? [英] Shorter syntax for casting from a List<X> to a List<Y>?
本文介绍了从List< X>转换的较短语法到列表< Y> ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道可以一次将一种类型的项目列表转换为另一种类型(假设您的对象具有公共静态显式运算符方法进行转换),如下所示:
I know its possible to cast a list of items from one type to another (given that your object has a public static explicit operator method to do the casting) one at a time as follows:
List<Y> ListOfY = new List<Y>();
foreach(X x in ListOfX)
ListOfY.Add((Y)x);
但是不可能一次转换整个列表吗?例如,
But is it not possible to cast the entire list at one time? For example,
ListOfY = (List<Y>)ListOfX;
推荐答案
如果真的可以将X
强制转换为Y
,则应该可以使用
If X
can really be cast to Y
you should be able to use
List<Y> listOfY = listOfX.Cast<Y>().ToList();
需要注意的一些事情(向评论者致敬!)
Some things to be aware of (H/T to commenters!)
- 您必须包含
using System.Linq;
才能获取此扩展方法 - 这将强制转换列表中的每个项目-而不是列表本身.调用
ToList()
将创建一个新的List<Y>
. - 此方法不支持自定义转换运算符. (请参见 http://stackoverflow.com/questions/14523530/为什么linq-cast-helper不能与隐式播放操作符一起工作)
- 此方法不适用于具有显式运算符方法(框架4.0)的对象
- You must include
using System.Linq;
to get this extension method - This casts each item in the list - not the list itself. A new
List<Y>
will be created by the call toToList()
. - This method does not support custom conversion operators. ( see http://stackoverflow.com/questions/14523530/why-does-the-linq-cast-helper-not-work-with-the-implicit-cast-operator )
- This method does not work for an object that has a explicit operator method (framework 4.0)
这篇关于从List< X>转换的较短语法到列表< Y> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文