2016-05-11 37 views
3

是否有可能在下面的例子中我是拳擊一個struct名爲分數,到隨後拆箱struct例如分子的特定成員?的Unbox具體結構成員

using system; 

struct fraction 
    { 
     public int numerator; 
     public int denominator; 
    } 

class Program 
    { 
     static void Main() 
     { 
      fraction f1; 
      f1.denominator = 100; 
      f1.numerator = 10; 
      object obj = f1; 

      // initializing f2. 
      fraction f2 = new fraction(); 
      // Or can unbox the obj to the f2 like this. 
      f2 = (fraction)obj; 
      // But if i want to only unbox the numerator member of the struct fraction boxed inside the obj Something like this will not work 
      f2.numerator = (fraction)obj.numerator; 
     } 
    } 
+0

你可以使用'((分數)obj).numerator',不是? –

+0

@GrantWinney抱歉不明白你的意思,你能解釋一下嗎?編輯:現在謝謝你的作品,你可以解釋爲什麼一個額外的括號是必要的? – Johnson

+0

我的意思是說,在一個步驟中取消裝箱和訪問該字段相對容易。 –

回答

1

如果不拆箱整個對象,則無法取消個別字段的裝箱。

但也許你只是想訪問該領域,並不確定正確的語法。當你拆箱原始對象,你可以通過引用未裝箱的值訪問現場:

fraction f2 = new fraction(); 
fraction originalFraction = (fraction)obj; // unbox the object 
int numerator = originalFraction.numerator; // access the field on the unboxed fraction 
f2.numerator = numerator; 

可以縮短,爲單行線,使用object initialization,雖然最終它做同樣的事情,上面的代碼:

fraction f2 = new fraction { numerator = ((fraction)obj).numerator }; 
4

無法取消裝箱整個對象時,無法取消裝箱對象的成員或屬性。

對象只能在裝箱狀態下作爲System.Object訪問。對原始類型的任何操作都需要拆箱。