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

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

    The reason is that a generic class like List<> is, for most purposes, treated externally as a normal class. e.g. when you say List() the compiler says ListString() (which contains strings). [Technical folk: this is an extremely plain-English-ified version of what's going on]

    Consequently, obviously the compiler can't be smart enough to convert a ListString to a ListObject by casting the items of its internal collection.

    That's why there's extension methods for IEnumerable like Convert() that allow you to easily supply conversion for the items stored inside a collection, which could be as simple as casting from one to another.

提交回复
热议问题