c#4.0: int a real subtype of object? covariance, ienumerable and value types

前端 未结 4 1234
鱼传尺愫
鱼传尺愫 2021-01-02 09:18

I wonder why IEnumerable can\'t be assigned to a IEnumerable. After all IEnumerable is one of the few interfa
4条回答
  •  猫巷女王i
    2021-01-02 09:51

    Value types aren't LSP-subtypes of object until they're boxed.

    Variance doesn't work with value types. At all.


    Demonstration that int is not a proper subtype (subtype in the LSP sense) of object:

    Works:

    object x = new object();
    lock (x) { ... }
    

    Does not work (substitutability violated):

    int y = new int();
    lock (y) { ... }
    

    Returns true:

    object x = new object();
    object a = x;
    object b = x;
    return ReferenceEquals(a, b);
    

    Returns false (substitutability violated):

    int y = new int();
    object a = y;
    object b = y;
    return ReferenceEquals(a, b);
    

    Of course, the topic of the question (interface variance) is a third demonstration.

提交回复
热议问题