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

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

    This has a lot to do with covariance, e.g., generic types are considered as parameters, and if the parameters do not resolve properly to a more specific type then the operation fails. The implication of such is that you really cannot cast to a more general type like object. And as stated by Rex, the List object won't convert each object for you.

    You might want to try the ff code instead:

    List sl = new List();
    //populate sl
    List ol = new List(sl);
    
    
    

    or:

    List ol = new List();
    ol.AddRange(sl);
    
    
    

    ol will (theoretically) copy all the contents of sl without problems.

    提交回复
    热议问题