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

前端 未结 9 996
我在风中等你
我在风中等你 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:26

    If you have a list of type List you can call list.add(new Baz()); assuming Baz implements IFoo. However you can't do that with a List, so you can't use a List everywhere you can use a List.

    However since Bar implements IFoo, you can use a Bar everywhere you use IFoo, so passing a Bar to add works when it expects and IFoo.

提交回复
热议问题