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

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

    I have a:

    private List<Leerling> Leerlingen = new List<Leerling>();
    

    And I was going to fill it with data collected in an List<object> What finally worked for me was this one:

    Leerlingen = (List<Leerling>)_DeserialiseerLeerlingen._TeSerialiserenObjecten.Cast<Leerling>();
    

    .Cast it to the type you want to get an IEnumerable from that type, then typecast the IEnemuerable to the List<> you want.

    0 讨论(0)
  • 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<object> would seem to allow) - because your code would crash then (because the list really is List<string> 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...

    0 讨论(0)
  • 2020-11-22 04:24

    Such covariance on generics is not supported, but you can actually do this with arrays:

    object[] a = new string[] {"spam", "eggs"};
    

    C# performs runtime checks to prevent you from putting, say, an int into a.

    0 讨论(0)
  • 2020-11-22 04:25
    List<string> sl = new List<string>();
    List<object> ol;
    ol = new List<object>(sl);
    
    0 讨论(0)
  • 2020-11-22 04:30

    Mike - I believe contravariance isn't allowed in C# either

    See Generic type parameter variance in the CLR for some more info.

    0 讨论(0)
  • 2020-11-22 04:31

    Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!

    As a side note, I think it would be more significant whether or not you can do the reverse cast:

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

    I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.

    Does anybody know or can test if such a cast is legal in C#?

    0 讨论(0)
提交回复
热议问题