Cannot convert from List to List

后端 未结 3 1897
我在风中等你
我在风中等你 2021-02-01 13:33

I have a set up like this:

abstract class Foo {}
class Bar : Foo {}

and a method elsewhere of this form:

void AddEntries(List&l         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 14:05

    This is not allowed for a simple reason. Assume the below compiles:

    AddEntries(new List());
    
    void AddEntries(List list)
    {
       // list is a `List` at run-time
       list.Add(new SomethingElseDerivingFromFoo()); // what ?!
    }
    

    If your code would compile, you have an unsafe addition (which makes the whole generic lists pointless) where you added SomethingElseDerivingFromFoo to actually a List (runtime type).

    To solve your problem, you can use generics:

    void AddEntries(List list) where T:Foo
    {
    
    }
    

提交回复
热议问题