扩展方法ConvertAll

编程入门 行业动态 更新时间:2024-10-26 08:20:46
本文介绍了扩展方法ConvertAll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

正确使用ConverAll是什么?它将一种类型转换为另一种类型吗?

What is the proper use of ConverAll ? Will it convert one type to another type?

喜欢

List<int> intList = new List<int>(); intList.Add(10); intList.Add(20); intList.Add(30); intList.Add(33); var query= intList.ConvertAll(x=>(double)x);

为此,我可以使用cast或OfType<>.

for this i can use cast or OfType<>.

推荐答案

ConvertAll 不是扩展方法,它是List<T>本身的真实方法.

它返回一个包含转换后元素的新列表.因此,在您的示例中,query变量实际上不是查询,而是List<double>.

It returns a new list containing the converted elements. So in your example, the query variable isn't actually a query, it's a List<double>.

Cast 和 OfType are 扩展方法,它们在IEnumerable上运行并返回IEnumerable<T>.但是,它们不适合您指定的用途:Cast可以转换引用类型,但不能转换值类型,仅将其取消装箱. OfType不执行任何转换,它仅返回已具有指定类型的所有元素.

Cast and OfType are extension methods that operate on IEnumerable and return an IEnumerable<T>. However they're not suitable for your stated purpose: Cast can convert reference types but cannot convert value types, only unbox them. OfType doesn't perform any conversion, it just returns any elements that are already of the specified type.

更多推荐

扩展方法ConvertAll

本文发布于:2023-11-05 18:59:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   ConvertAll

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!