Добавление пользовательских атрибутов с помощью mono.cecil?
Я не могу понять, как добавить настраиваемый атрибут к методу с помощью Mono.Cecil
Атрибуты, которые я хотел бы добавить, следующие:
.custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 )
Кто-нибудь знает, как добавить пользовательские атрибуты
Ответы
Ответ 1
На самом деле это очень просто.
ModuleDefinition module = ...;
MethodDefinition targetMethod = ...;
MethodReference attributeConstructor = module.Import(
typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes));
targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
module.Write(...);
Ответ 2
Это мой прием,
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 немного отличается. Я не уверен, что это потому, что он использует более новую версию Cecil или потому, что я ошибаюсь:)
В моей версии Cecil Import
возвращает TypeReference
, а не конструктор.