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

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

    You cannot cast between generic types with different type parameters. Specialized generic types don't form part of the same inheritance tree and so are unrelated types.

    To do this pre-NET 3.5:

    List sl = new List();
    // Add strings to sl
    
    List ol = new List();
    
    foreach(string s in sl)
    {
        ol.Add((object)s);  // The cast is performed implicitly even if omitted
    }
    
    
    

    Using Linq:

    var sl = new List();
    // Add strings to sl
    
    var ol = new List(sl.Cast());
    
    // OR
    var ol = sl.Cast().ToList();
    
    // OR (note that the cast to object here is required)
    var ol = sl.Select(s => (object)s).ToList();
    
        

    提交回复
    热议问题