linq - 类型转换和Linq Cast <T>()

标签 linq extension-methods linq-to-objects casting

尝试回答this question时,我发现了以下内容:

string s = "test";

var result1 = s.Select(c => (ushort)c); // works fine

var result2 = s.Cast<ushort>(); // throws an invalid cast exception

为什么Cast<T>()在这里失败?有什么不同?

最佳答案

想您会在这里找到答案:

Puzzling Enumerable.Cast InvalidCastException

最后一部分,在“编辑”下:

Cast<T>() is an extension method on IEnumerable rather than IEnumerable<T>. That means that by the time each value gets to the point where it's being cast, it has already been boxed back into a System.Object

关于linq - 类型转换和Linq Cast <T>(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3361908/

相关文章:

c# - 如何在查询 XML 时在 LINQ 中添加 OR 条件?

.net - Entity Framework 中的多对多关系导致无限循环

c# - 将新列表发送到 C# 列表中的 LINQ 查询结果

vb.net - 如何在 Option Strict ON 的 VB.NET 项目中使用 System.Linq 扩展方法

go - 我可以通过 GO 中的方法扩展错误接口(interface)吗?

json - 有没有办法向 JSON 对象添加方法?

c# - 有没有办法概括 Action 和 Action<T>?

c# - 帮助 LINQ 投影

c# - 动态 LINQ 查询

c# - 使用 LINQ 和 C# 从旧列表创建新列表