Adding generic object to generic list in C#

前端 未结 5 1277
长发绾君心
长发绾君心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 02:37

    I don't know anything about Java's ? construct, but I think the following most closely preserves your existing syntax while also matching your description.

        class SomeClass
        {
        }
    
        class C
        {
            void Add(SomeClass item)
            {
                Type type = typeof(SomeClass);
                if (!list.ContainsKey(type))
                    list[type] = new List>();
                var l = (List>)list[type];
                l.Add(item);
            }
    
            public void Method(SomeClass obj)
            {
                Add(obj);
            }
            readonly Dictionary list = new Dictionary();
        }
    

    test it with the following:

        class Program
        {
            static void Main(string[] args)
            {
                var c = new C();
                var sc1 = new SomeClass();
                var sc2 = new SomeClass();
                c.Method(sc1);
                c.Method(sc2);
                c.Method(sc1);
                c.Method(sc2);
            }
        }
    

提交回复
热议问题