Adding generic object to generic list in C#

前端 未结 5 1274
长发绾君心
长发绾君心 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:41

    I don't think you can do this in C#... you would have to add the type parameter to the class:

    class C {
        void Method(SomeClass obj) {
            list.Add(obj);
        }
        List> list = new List>();
    }
    

    The other option would be to use an interface:

    class C {
    
        void Method(T obj)
             where T : ISomeClass {
            list.Add(obj);
        }
        List list = new List();
    }
    

提交回复
热议问题