为了使用自定义属性装饰成员,在CIL中定义数组文字的语法是什么?
我在CIL中编写一些.NET代码(使用ilasm.exe编译它),我需要用自定义属性修饰一个方法。该属性的构造函数将整数数组作为其唯一参数。我怎么能在CIL中做到这一点?
这是自定义属性构造函数的签名(我无法更改):
public FooAttribute(int[] values) {
// some hidden constructor stuff
}
如果我用C#编写(但我不能),这就是我装饰我的方法的方法:
[Foo(new int[] {1, 2, 3, 4})]
public string Bar() {
return "Some text";
}
使用ildasm.exe查看已编译的C#(通过逆向工程尝试和理解)给了我一个丑陋且无法使用的二进制文字。我尝试使用Reflector.NET,它看起来好多了,但是ilasm.exe在关键字“new”处抛出语法错误,所以我不能使用它:
.custom instance void SomeNamespace.FooAttribute::.ctor(int32[]) = { new int32[int32(4)] { int32(1), int32(2), int32(3), int32(4) } }
答案 0 :(得分:3)
很难猜出你的问题可能是什么。如果我将此属性应用于Program.Test()方法,我得到这个:
.method private hidebysig static void Test() cil managed
{
.custom instance void ConsoleApplication1.FooAttribute::.ctor(int32[]) = ( 01 00 04 00 00 00 01 00 00 00 02 00 00 00 03 00
00 00 04 00 00 00 00 00 )
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method Program::Test
通过ilasm.exe运行,没问题。请注意数组元素值(将代码段窗口向右滚动以查看它们)已经转换为将它们嵌入到属性构造函数数据表中所需的格式。 BitConverter.GetBytes()可以完成部分工作。 Ecma文档应具有该数据所需的格式。