编程语言
首页 > 编程语言> > c# – IL约束呼叫

c# – IL约束呼叫

作者:互联网

对于此代码:

class Program
{
    static void Main()
    {
        Console.WriteLine(new MyStruct().ToString());
    }

    struct MyStruct { }
}

C#编译器生成约束的callvirt IL代码.

This文章说:

For example, if a value type V overrides the Object.ToString() method, a call V.ToString() instruction is emitted; if it does not, a box instruction and a callvirt Object.ToString() instruction are emitted. A versioning problem can arise <…> if an override is later added.

所以,我的问题是:如果编译器生成一个盒子代码而不是一个受约束的调用,为什么在这种情况下会出现问题呢?

解决方法:

box指令创建相关实例的副本.允许值类型的实例方法修改它们被调用的实例,如果它们这样做,则在副本上静默调用该方法是错误的.

static class Program
{
    static void Main()
    {
        var myStruct = new MyStruct();
        Console.WriteLine(myStruct.i); // prints 0
        Console.WriteLine(myStruct.ToString()); // modifies myStruct, not a copy of myStruct
        Console.WriteLine(myStruct.i); // prints 1
    }

    struct MyStruct {
        public int i;
        public override string ToString() {
            i = 1;
            return base.ToString();
        }
    }
}

标签:c,cil,boxing
来源: https://codeday.me/bug/20190612/1223467.html