How do I convert a List to List?

后端 未结 5 1900
后悔当初
后悔当初 2020-12-30 19:04

I have an interface defined as:

public interface MyInterface {
     object foo { get; set; };
}

and a class that implements that interface:

5条回答
  •  悲哀的现实
    2020-12-30 19:30

    But a List is emphatically not a List.

    Think:

    interface IAnimal { }
    
    class Cat : IAnimal { }
    class Dog : IAnimal { }
    
    var list = new List { new Cat(), new Dog() };
    

    Then

    var cats = (List)list;
    

    Absurd!

    Also,

    var cats = list.Cast();
    

    Absurd!

    Further

    var cats = list.ConvertAll(x => (Cat)x);
    

    Absurd!

    Instead, you could say

    var cats = list.OfType();
    

提交回复
热议问题