Compiler Error 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;
}