为什么我不能修改取消装箱转换的结果? [英] Why can I not modify the result of an unboxing conversion?

查看:158
本文介绍了为什么我不能修改取消装箱转换的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct Point
{
    public int x;
    public int y;
}
void Main()
{
    Point p;
    p.x = 1;
    p.y = 1;
    Object o = p;
    ((Point) o).x = 4; // error
    ((Point) o).x = 5; // error
    ((Point) o).x = 6; // error
    p = (Point) o  // expect 6
}

为什么不编译为

ldloc.1 // o
unbox Point
ldc.i4.4
stfld Point.x

C ++ CLI允许的地方.

Where C++ CLI allows it.

对于那些不知道的人,unbox值类型的副本 a>,而是将指向该值的指针压入堆栈. 只有分配才能创建副本.

For those who don't know, unbox is not required to create a copy of value types, instead it pushes a pointer to the value on to the stack. Only assignment would create a copy.

推荐答案

由于值类型的工作原理,带框的Point是原始副本的副本,并且通过强制退回到Point对其进行拆箱"操作另一个副本.根据C#语言规范(第1.3节类型和变量"):

Because of how value types work, the boxed Point is a copy of the original, and "unboxing" it by casting back to Point creates yet another copy. From the C# language spec (§1.3, "Types and Variables"):

将值类型的值转换为对象类型时,将分配一个对象实例(也称为框")以保存该值,然后将值复制到该框中.相反,当将对象引用转换为值类型时,将检查所引用的对象是否是具有正确值类型的框,如果检查成功,则将框中的值复制出来.

When a value of a value type is converted to type object, an object instance, also called a "box," is allocated to hold the value, and the value is copied into that box. Conversely, when an object reference is cast to a value type, a check is made that the referenced object is a box of the correct value type, and, if the check succeeds, the value in the box is copied out.

修改副本无论如何也不会更改原始副本,因此允许它并没有多大意义.

Modifying the copy wouldn't change the original anyway, so it wouldn't make much sense to allow it.

至于C ++……嗯……当然,C#的规则不一定适用于它. :) CLR实际上在指针和引用方面比您最初想的要灵活得多,而C ++(以这种灵活性而著称)很可能会利用它.

As for C++...well...of course, the rules of C# don't necessarily apply to it. :) The CLR actually has quite a bit more flexibility with pointers and references than you'd first think, and C++ -- being known for such flexibility -- probably takes advantage of it.

这篇关于为什么我不能修改取消装箱转换的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆