In C#, why can't a List object be stored in a List<object> variable

前端 未结 14 1400
别跟我提以往
别跟我提以往 2020-11-22 03:42

It seems that a List object cannot be stored in a List variable in C#, and can\'t even be explicitly cast that way.

List sl = new List

        
14条回答
  •  遇见更好的自我
    2020-11-22 04:40

    Mm, thanks to previous comments I found two ways to find it out. The first one is getting the string list of elements and then casting it to IEnumerable object list:

    IEnumerable ob;
    List st = new List();
    ob = st.Cast();
    
    
    

    And the second one is avoiding the IEnumerable object type, just casting the string to object type and then using the function "toList()" in the same sentence:

    List st = new List();
    List ob = st.Cast().ToList();
    
    
    

    I like more the second way. I hope this helps.

    提交回复
    热议问题