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

前端 未结 4 1222
鱼传尺愫
鱼传尺愫 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条回答
  •  粉色の甜心
    2021-01-02 09:44

    Every value type in .net has a corresponding ("boxed") object type. Non-boxed value types are effectively outside the object type hierarchy, but the compiler will perform a widening from the value type to the boxed class type. It would be helpful to have a "class" Boxed which would support a widening conversions to and from T, but which would be a class type. Internally, I think that's what the compiler's doing implicitly, but I don't know any way to do it explicitly. For any particular type like "integer", there would be no difficulty defining a class which would behave as a Boxed should, but I don't know any way of doing such a thing in generic fashion.

提交回复
热议问题