【发布时间】:2011-04-02 09:46:59
【问题描述】:
有两个这样的属性:
[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = true)]
sealed class Test1Attribute : Attribute
{ }
[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = true)]
sealed class Test2Attribute : Attribute
{ }
它们很简单,什么都不做。
还有一个方法用这两个属性修饰:
public void Hello([Test1]string arg, [Test2] string arg2) { }
现在如果我用IL Dasm编译代码并反编译,我会看到方法“Hello”的IL代码是这样的:
.method public hidebysig instance void Hello(int32 arg, int32 arg2) cil managed
{
.param [1]
.custom instance void ConsoleApplication1.Test1Attribute::.ctor()
.param [2]
.custom instance void ConsoleApplication1.Test2Attribute::.ctor()
.maxstack 8
L_0000: nop
L_0001: ret
}
我们可以看到 Test1Attribute 和 Test2Attribute 都在 IL 代码中。 它的元数据是这样的:
MethodName: Hello (06000005)
Flags : [Public] [HideBySig] [ReuseSlot] (00000086)
RVA : 0x0000206b
ImplFlags : [IL] [Managed] (00000000)
CallCnvntn: [DEFAULT]
hasThis
ReturnType: Void
2 Arguments
Argument #1: String
Argument #2: String
2 Parameters
(1) ParamToken : (08000002) Name : arg flags: [none] (00000000)
CustomAttribute #1 (0c000010)
-------------------------------------------------------
CustomAttribute Type: 06000001
CustomAttributeName: ConsoleApplication1.Test1Attribute :: instance void .ctor()
Length: 4
Value : 01 00 00 00 > <
ctor args: ()
(2) ParamToken : (08000003) Name : arg2 flags: [none] (00000000)
CustomAttribute #1 (0c000012)
-------------------------------------------------------
CustomAttribute Type: 06000002
CustomAttributeName: ConsoleApplication1.Test2Attribute :: instance void .ctor()
Length: 4
Value : 01 00 00 00 > <
ctor args: ()
同样,这两个属性也在元数据中。
所以我很好奇:
- 为什么它们会同时出现在 IL 和元数据中?
-
是什么
.param [1] .custom 实例无效 ConsoleApplication1.Test1Attribute::.ctor() .参数 [2] .custom 实例 void ConsoleApplication1.Test2Attribute::.ctor()
是什么意思?它看起来不像指令。那么它们是什么?他们是做什么的?
谢谢
【问题讨论】:
-
不确定您的第一个问题:您想知道它们为什么会存在或为什么它们会出现在 IL和元数据中?
-
哦,我的意思是它们出现了两次,看起来有点冗长。