Adding generic object to generic list in C#

前端 未结 5 1279
长发绾君心
长发绾君心 2020-12-11 02:23

I have class where the relevant part looks like

class C {
    void Method(SomeClass obj) {
        list.Add(obj);
    }
    List l         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 02:47

    Unfortunately, there is no direct equivalent in C# 3.0 as generics are invariant. You'll be able to do something like this in a graceful manner using C# 4.0 safe co/contra-variance feature. To workaround it, you could inherit SomeClass from a nongeneric base and create a List instead. If each instance of the class should hold only one type, you could make the class itself generic and set the type parameter there.

提交回复
热议问题