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

查看:21
本文介绍了用于从 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!)

  • 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 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屋!

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