用于从 List<X> 进行转换的较短语法到列表<Y>? [英] Shorter syntax for casting from a List<X> to a List<Y>?
本文介绍了用于从 List<X> 进行转换的较短语法到列表<Y>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道可以将项目列表从一种类型转换为另一种类型(假设您的对象有一个公共静态显式运算符方法来进行转换),如下所示:
I know it's 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();
需要注意的一些事情(对评论者的 H/T!)
Some things to be aware of (H/T to commenters!)
- 你必须包含
using System.Linq;
来获取这个扩展方法 - 这会投射列表中的每个项目 - 而不是列表本身.将通过调用
ToList()
来创建一个新的List
. - 此方法不支持自定义转换运算符.(参见 为什么 LinqCast<> 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 Why does the Linq Cast<> helper not work with the implicit cast operator? )
- This method does not work for an object that has an explicit operator method (framework 4.0)
这篇关于用于从 List<X> 进行转换的较短语法到列表<Y>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文