How does a generic constraint prevent boxing of a value type with an implicitly implemented interface?

前端 未结 5 1991
南笙
南笙 2020-12-08 12:12

My question is somewhat related to this one: Explicitly implemented interface and generic constraint.

My question, however, is how the compiler enables a ge

5条回答
  •  执笔经年
    2020-12-08 12:26

    The ultimate goal is to get a pointer to the method table of the class so that the correct method can be called. That can't happen directly on a value type, it is just a blob of bytes. There are two ways to get there:

    • Opcodes.Box, implements the boxing conversion and turns the value type value into an object. The object has the method table pointer at offset 0.
    • Opcodes.Contrained, hands the jitter the method table pointer directly without the need for boxing. Enabled by the generic constraint.

    The latter is clearly more efficient.

提交回复
热议问题