How to add custom attribute without default constructor using mono.cecil

This question is related to this , but is not a duplicate. Jb posted there that the following snippet will work to add a custom attribute:

ModuleDefinition module = ...; MethodDefinition targetMethod = ...; MethodReference attributeConstructor = module.Import( typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes)); targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor)); module.Write(...); 

I would like to use something similar, but add a custom attribute whose constructor accepts two string parameters in its (single) constructor, and I would like to specify values ​​for them (obviously). Can anyone help?

+6
source share
2 answers

First you should get a link to the correct version of the constructor:

 MethodReference attributeConstructor = module.Import( typeof(MyAttribute).GetConstructor(new [] { typeof(string), typeof(string) })); 

Then you can just populate the user attributes with string arguments:

 CustomAttribute attribute = new CustomAttribute(attributeConstructor); attribute.ConstructorArguments.Add( new CustomAttributeArgument( module.TypeSystem.String, "Foo")); attribute.ConstructorArguments.Add( new CustomAttributeArgument( module.TypeSystem.String, "Bar")); 
+12
source

Here's how to set the Named Parameters of a custom attribute that completely bypasses setting the attribute value using its constructors. As a note, you cannot set the CustomAttributeNamedArgument.Argument.Value parameter or even the CustomAttributeNamedArgument.Argument parameter directly, as they are readonly.

The following is equivalent to setting - [XXX(SomeNamedProperty = {some value})]

  var attribDefaultCtorRef = type.Module.Import(typeof(XXXAttribute).GetConstructor(Type.EmptyTypes)); var attrib = new CustomAttribute(attribDefaultCtorRef); var namedPropertyTypeRef = type.Module.Import(typeof(YYY)); attrib.Properties.Add(new CustomAttributeNamedArgument("SomeNamedProperty", new CustomAttributeArgument(namedPropertyTypeRef, {some value}))); method.CustomAttributes.Add(attrib); 
+2
source

Source: https://habr.com/ru/post/913931/


All Articles