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

前端 未结 4 1249
醉酒成梦
醉酒成梦 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: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((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(i => i))
    {
         Console.WriteLine(item.Test1);
    }
    

提交回复
热议问题