Why does the Linq Cast<> helper not work with the implicit cast operator?

前端 未结 3 1821
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 14:12

Please read to the end before deciding of voting as duplicate...

I have a type that implements an implicit cast operator to another type:

3条回答
  •  青春惊慌失措
    2020-12-01 15:06

    The short answer would be simply: the Cast method doesn't support custom conversion operators.

    In the first example:

    B b = a;
    B b2 = (B)a;
    

    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; 
    

    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).

    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;
    

提交回复
热议问题