在为整数类型调用ToString时涉及拳击吗? [英] Is boxing involved when calling ToString for integer types?

查看:44
本文介绍了在为整数类型调用ToString时涉及拳击吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:

int a = 5;
string str = a.ToString();

由于 ToString 是System.Object的虚拟方法,是否意味着每次我为整数类型调用此方法时,都会发生装箱运动?

Since ToString is a virtual method of System.Object, does it mean that everytime I call this method for integer types, a boxing occurs?

推荐答案

您已经得到答案,告诉您,对于值类型覆盖 ToString()时,当没有装箱时您称呼它为好,但是有一些实际看到它的方法真是太好了.

You've already got answers telling you that when ToString() is overridden for a value type, there will be no boxing when you call it, but it's nice to have some way of actually seeing that.

采用类型 int?( Nullable< int> ).这是一个有用的类型,因为它是一个值类型,但是装箱可能会产生空引用,并且不能通过空引用调用实例方法.它确实有一个覆盖的 ToString()方法.它没有(也不能有)重写的 GetType()方法.

Take the type int? (Nullable<int>). This is a useful type because it is a value type, yet boxing may produce a null reference, and instance methods cannot be called through a null reference. It does have an overridden ToString() method. It does not have (and cannot have) an overridden GetType() method.

int? i = null;
var s = i.ToString(); // okay: initialises s to ""
var t = i.GetType(); // not okay: throws NullReferenceException

这表明调用 i.ToString()中没有拳击,但是调用 i.GetType()中有拳击.

This shows that there is no boxing in the call i.ToString(), but there is boxing in the call i.GetType().

这篇关于在为整数类型调用ToString时涉及拳击吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆