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

前端 未结 14 1374
别跟我提以往
别跟我提以往 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:48

    If you're using .NET 3.5 have a look at the Enumerable.Cast method. It's an extension method so you can call it directly on the List.

    List sl = new List();
    IEnumerable ol;
    ol = sl.Cast();
    
    
    

    It's not exactly what you asked for but should do the trick.

    Edit: As noted by Zooba, you can then call ol.ToList() to get a List

    提交回复
    热议问题