Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

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

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

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;

...so how come Linq's .Cast<> doesn't?

A[] aa = new A[]{...};
var bb = aa.Cast<B>();  //throws InvalidCastException

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;

So why does my explicit cast work, but not the one inside .Cast<>?

Does the compiler sugar-up my explicit cast ?

PS. I saw this question but I don't think its answers really explain what's going on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So why my explicit cast work, and the one inside .Cast<> doesn't?

Your explicit cast knows at compile time what the source and destination types are. The compiler can spot the explicit conversion, and emit code to invoke it.

That isn't the case with generic types. Note that this isn't specific to Cast or LINQ in general - you'd see the same thing if you tried a simple Convert method:

public static TTarget Convert<TSource, TTarget>(TSource value)
{
    return (TTarget) value;
}

That will not invoke any user-defined conversions - or even conversions from (say) int to long. It will only perform reference conversions and boxing/unboxing conversions. It's just part of how generics work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...