首页 > 代码库 > box unboxing C#编程指南

box unboxing C#编程指南

box在堆栈中创建一个新的对象,性能消耗大
int i = 123;
// Boxing copies the value of i into object o.
object o = i;  
<style type="text/css">.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } </style>

image

 

 

unboxing  1.检查对象实例

               2.将该值从实例复制到值类型变量中

 

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing
<style type="text/css">.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } </style>

image

 

装箱和折箱都会引用性能的消耗,如:ArrayList使用泛型集合:(List<T>) 来避免box

参考自:http://msdn.microsoft.com/zh-cn/library/yz2be5wk.aspx

http://msdn.microsoft.com/zh-cn/library/ms173196.aspx