方法调用的一个结构?结构、方法

2023-09-03 12:09:02 作者:浪人

当我们在一对象调用方法,那么该对象的引用被隐式传递到方法中。

When we invoke a method on a object, then the reference of the object is passed implicitly to the method.

所以我的问题是当一个结构被调用的方法会发生什么情况?它是类似的类在这方面?

So my question is what happens when a method is invoked on a struct ? Is it similar to classes in this aspect?

推荐答案

根据该的 CIL规范中的指针按引用传递/作为托管指针。作为二进制杞人忧天以为这是一个CIL的功能。

According to the CIL spec the this pointer is passed by reference / as managed pointer. As Binary Worrier assumed this is a CIL feature.

实例和虚拟的方法   课程费用为coded到期望   参照类的实例   作为this指针。 相比之下,   实例和价值虚方法   类型应为coded到期望   托管指针(请参阅分区I)到   值类型的拆箱实例。   该CLI应转换装箱值   键入到托管指针   拆箱值类型时,装箱值   类型被当作this指针   一个虚拟的方法,它的实现   被装箱值类型提供的。

Instance and virtual methods of classes shall be coded to expect a reference to an instance of the class as the this pointer. By contrast, instance and virtual methods of value types shall be coded to expect a managed pointer (see Partition I) to an unboxed instance of the value type. The CLI shall convert a boxed value type into a managed pointer to the unboxed value type when a boxed value type is passed as the this pointer to a virtual method whose implementation is provided by the unboxed value type.

因此​​,从高层次的角度来看,电话为引用类型(类)的实例方法是这样的:

So from a high-level perspective a call to an instance method of a reference type (class) looks like this:

MyClass myClass = MyClass_Constructor();

MyClass_MyInstanceMethod(myClass, myFirstParameter);
//                       ^
//                       The "this" argument

和调用值类型(结构)这样的实例方法:

And a call to an instance method of a value type (struct) like this:

MyStruct myStruct = MyStruct_Constructor();

MyStruct_MyInstanceMethod(ref myStruct, myFirstParameter);
//                        ^
//                        The "this" argument