c# - Generics List<List> -


If I have list gt; is the type of MyClass , for example list & lt; List & lt; MyClass & gt; & Gt; and MyClass to MyClassB is the original class. Why can not I do the following?

  list & lt; List & lt; MyClass & gt; & Gt; All List = New List & lt; List & lt; MyClass & gt; & Gt; (); & Lt; MyClassB & gt; MyList = new list & lt; MyClassB & gt; (); MyList.Add (New MyClassB ()); // And now the point all lists do not work. Add (my list);   

If I apply a method, then I can say SomeClass & lt; T & gt; ... where t: myclass , is there anything like my list problem?

So that I will add any child category list to my first-level list?

The reason for this is not that you can do this: think allLists.Add (MyList) then the compiler will know that all the list [0] a list , so the following would be OK:

  all the listings [0]. Add (New MyClassX ());   

This will be a runtime error, because all the list [0] is actually a list . It is not capable of holding MyClassX objects

If you change your code, then myList a list , your code will work:

  list & lt; MyClass & gt; MyList = new list & lt; MyClass & gt; (); MyList.Add (New MyClassB ()); // This works because MyClassB expands MyClass allLists. Add (myList); // This also works,    

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -