当对整数文字(例如 ToString)调用对象方法时,CLR 是否首先装箱文字?
我想知道是否进行装箱以便在整数字面 (5) 上调用 ToString():
5.ToString();
哦,如果没有,那么发生了什么才能让 CLR 能够调用 ToString() 方法?
I wonder if boxing is taking place in order for ToString() to be called on the integer literal (5):
5.ToString();
Oh, and if not, what is taking place in order for the CLR to be able to call the ToString() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这不需要装箱 - 因为
int
覆盖ToString
。编译器可以准确地确定将调用哪个方法,因此不需要经过虚拟分派。它甚至不使用 callvirt - 该调用将对应于If you don override
ToString()
(etc) in a struct, then requests to the virtual方法需要拳击。No, that doesn't require boxing - because
int
overridesToString
. The compiler can determine exactly which method will be called, so it doesn't need to go through virtual dispatch. It doesn't even use callvirt - that call will correspond to IL ofIf you don't override
ToString()
(etc) in a struct, then calls to the virtual method will require boxing.