Why can I not modify the result of an unboxing conversion?

后端 未结 3 1353
说谎
说谎 2020-12-01 22:04
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
    ((Poi         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 23:06

    You can accomplish this using the System.Runtime.CompilerService.Unsafe.Unbox function:

        static void Main()
        {
            Point p;
            p.x = 1;
            p.y = 1;
            Object o = p;
            Unsafe.Unbox(o).x = 6; // error
            p = (Point)o;  // 6
            Console.WriteLine(p.x);
        }
    

    As the documentation notes, and I presume the reason it is considered unsafe, is that you must not do this with an immutable built-in type [e.g. Unbox(i) = 42], and the system does nothing to enforce this.

提交回复
热议问题