ToString() 会发生装箱吗?
最近被問到了這個問題,我當時回答是會的,因為ToString()會把值類型轉換成引用類型,所以會發生裝箱。
后來總覺有些不妥當,所以查閱一些資料并參考網絡上的討論:
拆箱裝箱的官方解釋:
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.
裝箱用于在托管內存中存儲值類型。?裝箱是是值類型到?object?類型或到此值類型所實現的任何接口類型的隱式轉換。?對值類型裝箱會在堆中分配一個對象實例,并將該值復制到新的對象中。
下面是官方的幾個拆箱/裝箱的例子:
eg1: int?i?=?123; object?o?=?i;//隱式裝箱eg2: String.Concat("Answer",?42,?true)?//42和true都會發生裝箱eg3: List<object>?mixedList?=?new?List<object>(); mixedList.Add("First?Group:"); for?(int?j?=?1;?j?<?5;?j++) {mixedList.Add(j);//在添加時,j先裝箱 } var?sum?=?0;for?(var?j?=?1;?j?<?5;?j++) {//下面的一行會發生編譯錯誤:?//Operator?'*'?cannot?be?applied?to?operands?of?type?'object'?and?'object'.?//sum?+=?mixedList[j]?*?mixedList[j]);//下面經過拆箱就不會出現上面的編譯錯誤.sum?+=?(int)mixedList[j]?*?(int)mixedList[j]; }Note:?
相對于簡單的賦值而言,裝箱和取消裝箱過程需要進行大量的計算。?對值類型進行裝箱時,必須分配并構造一個新對象。?取消裝箱所需的強制轉換也需要進行大量的計算,只是程度較輕。
更多性能的了解:https://msdn.microsoft.com/zh-cn/library/ms173196.aspx
再引入圖片來在說明內存中的變化:
int?i?=?123; object?o?=?i;//隱式裝箱看值類型有沒有進行拆箱,就看他有沒有裝換成Object或者值類型所繼承的接口類型...
Int.ToString 此方法中,值類型轉換成ValueType類型,不滿足裝箱的條件(可以查看下面IL代碼),可以判定Int.ToString是沒有裝箱的。
了解了上面的信息之后以后就知道下面建議用哪一個了吧:
int?num?=?3; //用下面的哪個呢?請思考 string?numStr?=?string.Format("{0}",?num); string?numStr?=?string.Format("{0}",?num.ToString());參考:
https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
http://www.cnblogs.com/DebugLZQ/archive/2012/09/02/2667835.html
http://q.cnblogs.com/q/44027
http://bbs.csdn.net/topics/360191652
轉載于:https://blog.51cto.com/lybing/1790605
總結
以上是生活随笔為你收集整理的ToString() 会发生装箱吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 花香蝶自聚 草盛马自来
- 下一篇: C#截屏