In C#, why can't a List object be stor

2018-12-31 05:30发布

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<string> sl = new List<string>();
List<object> ol;
ol = sl;

results in Cannot implicitly convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object>

And then...

List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;

results in Cannot convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object>

Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.

14条回答
冷夜・残月
2楼-- · 2018-12-31 06:29

Yes, you can, from .NET 3.5:

List<string> sl = new List<string>();
List<object> ol = sl.Cast<object>().ToList();
查看更多
只若初见
3楼-- · 2018-12-31 06:30

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

public IList<B> ConvertIList<D, B>(IList<D> list) where D : B
{
    List<B> newList = new List<B>();

    foreach (D item in list)
    {
        newList.Add(item);
    }

    return newList;
}

(Based on Zooba's example)

查看更多
登录 后发表回答