IL constrained call

北城以北 提交于 2019-12-10 16:16:02

问题


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?


回答1:


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();
        }
    }
}


来源:https://stackoverflow.com/questions/28395401/il-constrained-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!