2014-01-28 70 views
0

來自c + +背景,我總是對值類型感到困惑。 如果你在一個valuetype上調用一個構造函數,它是否總是會導致裝箱? 例如,c#拳擊價值類型

public struct myvaltype 
{ 
    public int x; 
    public int y; 


    public myvaltype(int thisx,int thisy) 
    { 
     x = thisx; 
     y = thisy; 
    } 

} 

myvaltype tsts1 = new myvaltype(); 
myvaltype tsts2 = new myvaltype(8, 9); 

做這兩個構造函數調用的原因拳擊? 如果是,那麼避免裝箱的唯一方法是手動設置每個成員對象(x,y)?

+0

爲什麼你會期望在這個例子中的任何拳擊? – ken2k

+0

來自C++應該很容易在C#中使用值類型。如果你想象每個引用類型中的'*',C#的行爲類似於C++(比如想象'string'真的是「string *」,因爲它是引用類型)。 C#有與缺省淺拷貝相關的問題和錯誤地修改值類型的臨時拷貝... –

回答

3

不,這裏沒有拳擊

裝箱是將值類型轉換爲類型對象或由此值類型實現的任何接口類型的過程。

Boxing and Unboxing (C# Programming Guide)

您未投放(或明或暗地)值類型object或接口。

會有拳擊(和拆箱),如果你的構造看上去就像是:

public myvaltype(object thisx, object thisy) 
{ 
    x = (int)thisx; 
    y = (int)thisy; 
}