Why covariance and contravariance do not support value type

前端 未结 4 1711
耶瑟儿~
耶瑟儿~ 2020-11-22 00:46

IEnumerable is co-variant but it does not support value type, just only reference type. The below simple code is compiled successfully:

<
4条回答
  •  抹茶落季
    2020-11-22 01:07

    I think everything starts from definiton of LSP (Liskov Substitution Principle), which climes:

    if q(x) is a property provable about objects x of type T then q(y) should be true for objects y of type S where S is a subtype of T.

    But value types, for example int can not be substitute of object in C#. Prove is very simple:

    int myInt = new int();
    object obj1 = myInt ;
    object obj2 = myInt ;
    return ReferenceEquals(obj1, obj2);
    

    This returns false even if we assign the same "reference" to the object.

提交回复
热议问题