C# List: why you cannot do `List foo = new List();`

前端 未结 9 985
我在风中等你
我在风中等你 2020-12-02 20:05

If you have an Interface IFoo and a class Bar : IFoo, why can you do the following:

List foo = new List();          


        
9条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 20:11

    I used some linq to make the conversion easier

    List bar = new List();
    bar.add(new Bar());
    
    List foo = bar.Select(x => (IFoo)x).ToList();
    

    It is a little less versbose than other answers but works well

提交回复
热议问题