コンパイラ エラー CS0445

アンボックス変換の結果を変更できません

アンボックス変換の結果は一時変数に格納されます。 一時変数に対して行った変更は一時的にしか維持されないため、コンパイラでは、このような変数に変更を加えることを許可していません。 これを修正するには、中間式を格納する新しい値型の変数を宣言し、その変数へのボックス化解除の変換の結果を代入します。

次のコードでは CS0455 が生成されます。

// CS0445.CS  
class UnboxingTest  
{  
    public static void Main()  
    {  
        Point p;  
        p.x = 1;  
        p.y = 2;  
        object obj = p;  
        // The following line generates CS0445, because the result  
        // of unboxing obj is a temporary variable.  
        ((Point)obj).x = 2;  
  
        // The following lines resolve the error.  
  
        // Store the result of the unboxing conversion in p2.  
        Point p2;
        p2 = (Point)obj;  
        // Then you can modify the unboxed value.  
        p2.x = 2;  
    }  
}  
  
struct Point  
{  
    public int x, y;  
}