在 CIL 中定义自定义属性
为了用自定义属性修饰成员,在 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) } }
What is the syntax for defining an array literal in CIL for the purposes of decorating a member with a custom attribute?
I am writing some .NET code in CIL (using ilasm.exe to compile it) and I need to decorate a method with a custom attribute. The constructor for that attribute takes an array of integers as its only parameter. How can I do this in CIL?
This is the signature of the custom attribute's constructor (I can't change it):
public FooAttribute(int[] values) {
// some hidden constructor stuff
}
This is how I'd decorate my method if I were writing in C# (but I can't):
[Foo(new int[] {1, 2, 3, 4})]
public string Bar() {
return "Some text";
}
Using ildasm.exe to look at the compiled C# (to try and understand by reverse engineering) gives me an ugly and unusable binary literal. I tried using Reflector.NET instead and it looks much better but ilasm.exe throws a syntax error at the keyword "new" so I can't use it:
.custom instance void SomeNamespace.FooAttribute::.ctor(int32[]) = { new int32[int32(4)] { int32(1), int32(2), int32(3), int32(4) } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很难猜测你的问题可能是什么。如果我将此属性应用于 Program.Test() 方法,我会得到以下信息:
通过 ilasm.exe 运行此命令,没问题。请注意数组元素值(将片段窗口向右滚动以查看它们)如何已转换为将它们嵌入到属性构造函数数据表中所需的格式。 BitConverter.GetBytes() 可以完成部分工作。 Ecma 文档应具有该数据所需的格式。
Hard to guess what your problem might be. If I apply this attribute to a Program.Test() method, I get this:
Run this through ilasm.exe, no problem. Note how the array element values (scroll the snippet window to the right to see them) are already converted into the format needed to embed them in the attribute constructor data table. BitConverter.GetBytes() can get part of that job done. The Ecma document should have the required format of that data.