【发布时间】:2012-01-13 08:43:27
【问题描述】:
我不知道如何使用 Mono.Cecil 将自定义属性添加到方法中 我想添加的属性是这样的:
.custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 )
有谁知道如何添加自定义属性
【问题讨论】:
标签: c# mono.cecil
我不知道如何使用 Mono.Cecil 将自定义属性添加到方法中 我想添加的属性是这样的:
.custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 )
有谁知道如何添加自定义属性
【问题讨论】:
标签: c# mono.cecil
其实很简单。
ModuleDefinition module = ...;
MethodDefinition targetMethod = ...;
MethodReference attributeConstructor = module.Import(
typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes));
targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
module.Write(...);
【讨论】:
这是我的看法,
MethodDefinition methodDefinition = ...;
var module = methodDefinition.DeclaringType.Module;
var attr = module.Import(typeof (System.Diagnostics.DebuggerHiddenAttribute));
var attrConstructor = attr.Resolve().Constructors.GetConstructor(false, new Type[] {});
methodDefinition.CustomAttributes.Add(new CustomAttribute(attrConstructor));
我注意到 Jb Evain 的 sn-p 略有不同。我不确定那是因为他使用的是新版本的 Cecil 还是因为我错了:)
在我的 Cecil 版本中,Import 返回 TypeReference,而不是构造函数。
【讨论】:
Instruction.Create(OpCodes.Newarr, module.Import(typeof(Object)))) 创建一个新对象[]
我想详细说明 Jb Evain 的回答,关于如何将参数传递给属性。对于示例,我使用了System.ComponentModel.BrowsableAttribute 并将browsable 参数的值传递给它的构造函数:
void AddBrowsableAttribute(
ModuleDefinition module,
Mono.Cecil.ICustomAttributeProvider targetMember, // Can be a PropertyDefinition, MethodDefinition or other member definitions
bool browsable)
{
// Your attribute type
var attribType = typeof(System.ComponentModel.BrowsableAttribute);
// Find your required constructor. This one has one boolean parameter.
var constructor = attribType.GetConstructors()[0];
var constructorRef = module.ImportReference(constructor);
var attrib = new CustomAttribute(constructorRef);
// The argument
var browsableArg =
new CustomAttributeArgument(
module.ImportReference(typeof(bool)),
browsable);
attrib.ConstructorArguments.Add(browsableArg);
targetMember.CustomAttributes.Add(attrib);
}
此外,命名参数可以添加到创建的CustomAttribute 的Properties 集合中。
【讨论】: