Adding custom attributes using mono.cecil?

扶醉桌前 提交于 2019-12-21 03:32:50

问题


I can't figure how to add custom attribute to a method using Mono.Cecil The attributes that I would want to add is like this :

.custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) 

Does anyone know how to add custom attributes


回答1:


It's actually very easy.

ModuleDefinition module = ...;
MethodDefinition targetMethod = ...;
MethodReference attributeConstructor = module.Import(
    typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes));

targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
module.Write(...);



回答2:


This is my take,

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));

I noticed Jb Evain's snippet is slightly different. I'm not sure whether that is because is because he's using a newer version of Cecil or because I'm wrong :)

In my version of Cecil, Import returns a TypeReference, not the constructor.



来源:https://stackoverflow.com/questions/8388196/adding-custom-attributes-using-mono-cecil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!