boxing on structs when calling ToString()

前端 未结 3 1189
轮回少年
轮回少年 2020-12-28 10:31

I\'ve often wondered if the following scenario actually happens in c#

If I have a struct but I don\'t explicitly override any of the methods that derived from objec

3条回答
  •  天命终不由人
    2020-12-28 10:38

    If thisType is a value type and thisType does not implement method then ptr is dereferenced, boxed, and passed as the 'this' pointer to the callvirt method instruction.

    This last case can occur only when method was defined on Object, ValueType, or Enum and not overridden by thisType. In this case, the boxing causes a copy of the original object to be made.

    The answer is yes, the value type is boxed. This is why it is always a good thing to override ToString() on custom structs.

提交回复
热议问题