从List< X>转换的较短语法到列表< Y&gt ;? [英] Shorter syntax for casting from a List<X> to a List<Y>?

查看:64
本文介绍了从List< X>转换的较短语法到列表< Y&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以一次将一种类型的项目列表转换为另一种类型(假设您的对象具有公共静态显式运算符方法进行转换),如下所示:

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!)

  • 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 to ToList().
  • 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&lt; X&gt;转换的较短语法到列表&lt; Y&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆