什么是用于限定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在关键字抛出一个语法错误,“新”,所以我不能用它:

.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文件应该具有所需的数据格式。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top