Why does a Linq Cast operation fail when I have an implicit cast defined?

前端 未结 4 1221
醉酒成梦
醉酒成梦 2020-11-27 06:39

I\'ve created two classes, with one of them having an implicit cast between them:

public class Class1
{
    public int Test1;
}

public class Class2
{
    pu         


        
相关标签:
4条回答
  • 2020-11-27 07:00

    Because, looking at the code via Reflector, Cast doesnt attempt to take any implicit cast operators (the LINQ Cast code is heavily optimised for special cases of all kinds, but nothing in that direction) into account (as many .NET languages won't).

    Without getting into reflection and other things, generics doesnt offer any out of the box way to take such extra stuff into account in any case.

    EDIT: In general, more complex facilities like implicit/explict, equality operators etc. are not generally handled by generic facilities like LINQ.

    0 讨论(0)
  • 2020-11-27 07:04

    Thanks for that I was about to use that exact case somewhere. You have saved me a pile of time. As a possible solution to your problem you could use ConvertAll<> instead, like so:

    foreach (Class1 item in items.ConvertAll<Class1>((i) => (Class1)i))
    {
         Console.WriteLine(item.Test1);
    }
    

    EDIT: or if you want to be more explicit that the cast is implicit then this works too:

    foreach (Class1 item in items.ConvertAll<Class1>(i => i))
    {
         Console.WriteLine(item.Test1);
    }
    
    0 讨论(0)
  • 2020-11-27 07:18

    You can also use this to do casting with conversions if needed:

    public static IEnumerable<TDest> CastAll<TItem, TDest>(this IEnumerable<TItem> items)
    {
     var p = Expression.Parameter(typeof(TItem), "i");
     var c = Expression.Convert(p, typeof(TDest));
     var ex = Expression.Lambda<Func<TItem, TDest>>(c, p).Compile();
    
     foreach (var item in items)
     {
        yield return ex(item);
     }
    }
    

    From http://adventuresdotnet.blogspot.com/2010/06/better-more-type-safe-alternative-to.html

    0 讨论(0)
  • 2020-11-27 07:23

    A solution could be to use a bit of linq'ing here if you really need this kind of conversion:

    List items = new List{new Class2{Test2 = 9}};
    foreach (Class1 item in (from x in items select (Class1)x))
    {
        Console.WriteLine(item.Test1);
    }
    
    0 讨论(0)
提交回复
热议问题