IL constrained call

2019-06-24 05:00发布

For this code:

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

    struct MyStruct { }
}

the C# compiler generates constrained callvirt IL code.

This article says:

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.

So, my question is: why would it be a problem in this case if the compiler will generate a box code, not a constrained call?

标签: c# cil boxing
1条回答
地球回转人心会变
2楼-- · 2019-06-24 05:39

The box instruction creates a copy of the instance in question. Instance methods of value types are permitted to modify the instance they're called on, and if they do, silently calling the method on a copy is the wrong thing to do.

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();
        }
    }
}
查看更多
登录 后发表回答