c# - 为什么 Enumerable.Cast<> 不使用我的转换运算符?

标签 c# linq

使用这种类型:

class Foo
{
  public static implicit operator int(Foo obj)
  {
    return 5;
  }
}

var test=new[] { new Foo() };

以下按预期工作

var ok=test.Select(x => (int)x).ToList();

但使用 Cast<> 失败并出现 InvalidCastException - 为什么?

var fail=test.Cast<int>().ToList();

最佳答案

阅读 Jon Skeet 关于重新实现 Linq (EduLinq) 的博客,特别是 part 33 ,他是这样说的:

It's worth noting that (as of .NET 3.5 SP1) Cast and OfType only perform reference and unboxing conversions. They won't convert a boxed int to a long, or execute user-defined conversions. Basically they follow the same rules as converting from object to a generic type parameter. (That's very convenient for the implementation!)

关于c# - 为什么 Enumerable.Cast<> 不使用我的转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791176/

相关文章:

c# - 如何将虚拟属性添加到密封类

c# - 指定的架构无效。错误 : The relationship was not loaded because the type is not available

c# - C# 4.0 中的方法重载与可选参数

c# - 用asp传递参数:Button onClick with x-jquery-tmpl

c# - 如何在 C# 中使用 LINQ 比较 2 个 XML

c# - 类型 'Contains' 1[System.Object] 上不存在方法 'System.Data.Linq.DataQuery`

C#:Resharper 的替代品,C# 版本

c# - 如何在 C# 中使用 NI 库中的 VI

c# - 获取两次之间的记录列表 C# Linq To Entities

C#:如何根据子元素的属性过滤 XML 文件的结果?