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

前端 未结 14 1397
别跟我提以往
别跟我提以往 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<string> sl = new List<string>();
    IEnumerable<object> ol;
    ol = sl.Cast<object>();
    

    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

    0 讨论(0)
  • 2020-11-22 04:48

    Yes, you can, from .NET 3.5:

    List<string> sl = new List<string>();
    List<object> ol = sl.Cast<object>().ToList();
    
    0 讨论(0)
提交回复
热议问题