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

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

    That's actually so that you don't try to put any odd "object" in your "ol" list variant (as List would seem to allow) - because your code would crash then (because the list really is List and will only accept String type objects). That's why you can't cast your variable to a more general specification.

    On Java it's the other way around, you don't have generics, and instead everything is List of object at runtime, and you really can stuff any strange object in your supposedly-strictly typed List. Search for "Reified generics" to see a wider discussion of java's problem...

    提交回复
    热议问题