IL约束通话 [英] IL constrained call

查看:139
本文介绍了IL约束通话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关此代码:

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

    struct MyStruct { }
}

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

the C# compiler generates constrained callvirt IL code.

文章说:

例如,如果一个值V型覆盖Object.ToString()方法,调用V.ToString()指令发出的;如果不是这样,一个盒子指令和callvirt Object.ToString()指令被发射。 。可能会出现一个版本问题< ...>如果一个覆盖后来加入

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?

推荐答案

指令可创建有问题的实例的副本。允许值类型的实例方法来修改他们是所谓的实例,如果他们这样做,静静地调用拷贝方法是错误的做法。

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

这篇关于IL约束通话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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