使用这种类型:
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/