为什么LINQ的演员LT;&GT;助手不与隐式转换运营商合作? [英] Why does the Linq Cast<> helper not work with the implicit cast operator?
问题描述
的请投票决定像以前读到结尾重复... 的
我有一个实现了 A型隐式转换
运营商为另一种类型:
I have a type that implements an implicit cast
operator to another type:
class A
{
private B b;
public static implicit operator B(A a) { return a.b; }
}
class B
{
}
现在,显性和隐性的铸造工作就好了:
Now, implicit and explicit casting work just fine:
B b = a;
B b2 = (B)a;
...所以怎么来的Linq的 .Cast&LT;&GT;
不?
A[] aa = new A[]{...};
var bb = aa.Cast<B>(); //throws InvalidCastException
在源$ C $ C
寻找 .Cast&LT;&GT;
,没有太多的神奇事情:一些特殊情况下,如果该参数确实是一个的IEnumerable&LT; B&GT;
,然后:
Looking at the source code for .Cast<>
, there's not much magic going on: a few special cases if the parameter really is a IEnumerable<B>
, and then:
foreach (object obj in source)
yield return (T)obj;
// ^^ this looks quite similar to the above B b2 = (B)a;
那么,为什么的我的的显式类型转换的工作,但不是一个内部 .Cast&LT;&GT;
?
So why does my explicit cast work, but not the one inside .Cast<>
?
该编译器糖了我明确的转换?
Does the compiler sugar-up my explicit cast ?
PS。只见这个问题但我不认为它真正的答案解释发生了什么事情。
PS. I saw this question but I don't think its answers really explain what's going on.
推荐答案
简短的答案是简单的:在演员LT; T&GT;
方法不支持自定义转换操作符
The short answer would be simply: the Cast<T>
method doesn't support custom conversion operators.
在第一个例子:
B b = a;
B b2 = (B)a;
编译器可以看到这个 B静态分析中(A一)
运营商;编译器间$ P $点这是一个静态呼叫
你的运营商定制的方法。在第二个例子中:
the compiler can see this B(A a)
operator during static analysis; the compiler interprets this as a static call
to your custom operator method. In the second example:
foreach (object obj in source)
yield return (T)obj;
这具有的没有知识的操作人员;这是通过 unbox.any
实施(这是一样的 castclass
如果 T
是一个引用类型)。
that has no knowledge of the operator; this is implemented via unbox.any
(which is the same as castclass
if T
is a ref-type).
还有第三个选择:如果通过动态
去的时候,运行时实现试图模仿编译器的规则,所以这个的将会的发现运营商......但并不像C#的一部分-to-IL编译步骤:
There is also a third option: if you went via dynamic
, the runtime implementation tries to mimic compiler rules, so this will find the operator ... but not as part of the C#-to-IL compile step:
dynamic b = a; // note that `dynamic` here is *almost* the same as `object`
B b2 = b;
这篇关于为什么LINQ的演员LT;&GT;助手不与隐式转换运营商合作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!