Why does calling an explicit interface implementation on a value type cause it to be boxed?

前端 未结 3 1704
日久生厌
日久生厌 2020-12-28 18:43

My question is somewhat related to this one: How does a generic constraint prevent boxing of a value type with an implicitly implemented interface?, but different because it

3条回答
  •  春和景丽
    2020-12-28 19:18

    The problem is that there's no such thing as a value or variable which is "just" an interface type; instead, when an attempt is made to define to such a variable or cast to such a value, the real type that is used is, effectively, "an Object that implements the interface".

    This distinction comes into play with generics. Suppose a routine accepts a parameter of type T where T:IFoo. If one passes such a routine a struct which implements IFoo, the passed-in parameter won't be a class type that inherits from Object, but will instead be the appropriate struct type. If the routine were to assign the passed-in parameter to a local variable of type T, the parameter would be copied by value, without boxing. If it were assigned to a local variable of type IFoo, however, the type of that variable would be "an Object that implements IFoo", and thus boxing would be required that that point.

    It may be helpful to define a static ExecF(ref T thing) where T:I method which could then invoke the I.F() method on thing. Such a method would not require any boxing, and would respect any self-mutations performed by I.F().

提交回复
热议问题