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

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

    Here is another pre-.NET 3.5 solution for any IList whose contents can be cast implicitly.

    public IList ConvertIList(IList list) where D : B
    {
        List newList = new List();
    
        foreach (D item in list)
        {
            newList.Add(item);
        }
    
        return newList;
    }
    

    (Based on Zooba's example)

提交回复
热议问题