IL“.custom instance void [attribute] = (...)”是什么意思?

What does the IL ".custom instance void [attribute] = (...)" mean?

当我对参数使用 params 关键字时,我在 IL 中找到了这一行。我从中了解到,调用了 ParamArrayAttribute class 的构造函数,但我不明白 01 00 00 00 是什么意思。

.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = (
            01 00 00 00
        )

当用于修饰成员时,属性可能包含将被发送到属性构造函数的初始化参数。

例如

[DataMember(EmitDefaultValue = true)]
public int Property { get; set; }

编译为

.custom instance void
[System.Runtime.Serialization]System.Runtime.Serialization.DataMemberAttribute::.ctor() = 
( 01 00 01 00 54 02 10 45 6D 69 74 44 65 66 61 75 6C 74 56 61 6C 75 65 01 )

你看到的字节码序列对应EmitDefaultValue参数的初始化

在你的情况下,

01 00 00 00

是没有参数传递给属性构造函数时使用的字节序列。

请参考第II.21节C# specification (version 6) defined in ECMA-335:

Custom attributes are declared using the directive .custom, followed by the method
declaration for a type constructor, optionally followed by a Bytes in parentheses:
CustomDecl ::=
    Ctor [ ‘=’ ‘(’ Bytes ‘)’ ]

Bytes 段的格式在第 II.23.3 节中定义:

CustomAttrib starts with a Prolog – an unsigned int16, with value 0x0001.
...
Next is a description of the optional “named” fields and properties. This starts with
NumNamed – an unsigned int16 giving the number of “named” properties or fields that
follow. Note that NumNamed shall always be present. A value of zero indicates that there
are no “named” properties or fields to follow (and of course, in this case, the
CustomAttrib shall end immediately after NumNamed).

VI.B.3.

部分提供了各种自定义属性的示例

ParamArrayAttribute的情况下,前两个字节(01 00)是Prolog(小端格式),最后两个字节(00 00) 是 NumNamed(0 = 无参数)。