EffectiveC 17 裝箱和拆箱的最小化

2022-08-09 05:24:13 字數 1022 閱讀 6314

1.如下這段**會經歷裝箱和拆箱。例如25會先裝箱成object後傳遞給writeline方法(一次拷貝),在方法內部又

經歷拆箱成int(第二次拷貝)後然後呼叫tostring().

console.writeline("a few numbers:, , ", 25, 32, 50);

所以建議這種寫法:只經歷一次裝箱

console.writeline("a few numbers:, , ", 25.tostring(), 32.tostring(), 50.tostring());

規則一:隱式需要object'型別時,值型別先裝箱。 

2.在使用.net 1.x的集合時,當你新增乙個值型別資料到集合時中,你就建立了乙個箱子。任何時候從集合中移出乙個物件時,你得到的是箱子裡的乙個拷貝。

struct person

// using the person in a collection:

arraylist attendees = new arraylist( );

person p = new person( "old name" );

attendees.add( p );

// try to change the name: would work if person was a reference type.

person p2 = (( person )attendees[ 0 ] );

p2.name = "new name";

// writes "old name":

console.writeline( attendees[ 0 ].tostring( ));

此段**有3處拷貝。person是乙個值型別資料,在儲存到arraylist之前它被裝箱。這會產生乙個拷貝。而在移出的persone物件上通過訪問屬性做一些修改時,另乙個拷貝被建立。而你所做的修改只是針對拷貝,而實際上還有第三個拷貝通過tostring()方法來訪問attendees[0]中的物件。

《Effective C 》之減少裝箱和拆箱

為了便於文章的開展,首先介紹裝箱 boxing 和拆箱 unboxing 這兩個名詞。net的型別分為兩種,一種是值型別,另一種是引用型別。這兩個型別的本質區別,值型別資料是分配在棧中,而引用型別資料分配在堆上。那麼 如果要把乙個值型別資料放到堆上,就需要裝箱操作 反之,把乙個放在堆上的值型別資料取...

裝箱和拆箱,自動裝箱和自動拆箱

以integer的建立為例。裝箱 把基本資料型別轉換成包裝類物件 int integer integer num1 new integer 17 拆箱 把乙個包裝類的物件,轉換成基本型別的變數 integer int int num2 num1.intvalue 自動裝箱 integer num3 ...

java 自動拆裝箱和手動拆裝箱

a integer類概述 integer 類在物件中包裝了乙個基本型別 int 的值,該類提供了多個方法,能在 int 型別和 string 型別之間互相轉換,還提供了處理 int 型別時非常有用的其他一些常量和方法 b 構造方法 public integer int value public in...