簡體   English   中英

在裝箱和拆箱操作中將預定義變量的值分配給對象類型變量

[英]Assign Predefined Variable's Value To Object Type Variable In Boxing And UnBoxing Actions

我想檢查C#中的裝箱和拆箱動作。 我在用戶定義的類中定義了變量(這是我的類)。 但是,當我想使用預定義的變量時,就會發生奇怪的錯誤。 我的代碼塊如下所示。

   public int i = 123;
   /*The following line boxes i.*/ 
   public object o = i; 
   o = 123;
   i = (int)o;  // unboxing

當我測試此代碼以查看C#中的裝箱和拆箱操作時,發生以下錯誤。

Error   3   Invalid token ')' in class, struct, or interface member declaration 
Error   4   Invalid token ';' in class, struct, or interface member declaration 
Error   1   Invalid token '=' in class, struct, or interface member declaration 
Error   2   Invalid token '=' in class, struct, or interface member declaration

我從來沒有遇到過這樣的錯誤。 我只想使用以前在用戶定義的類(我的類)中定義的變量。

您需要某種代碼結構:

class foo
{  
    public int I = 123; // is okay
    /*The following line boxes i.*/ 
    public object O = new object();

    foo()
    {
        // operations in a body
        O = 123;
        I = (int)O;  // unboxing
    }
}

在我看來,代碼行在類聲明中。 您可以在此處聲明和初始化變量,您可以在前兩行中進行操作。 但是,您不能在類范圍內做更多的事情。

最后兩行僅在方法范圍內有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM