为了用自定义属性装饰成员,在 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) } }
最佳答案
很难猜测你的问题可能是什么。如果我将此属性应用于 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 文档应具有该数据所需的格式。
关于.net - 在 CIL 中定义自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3023337/