Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values to attribute added dynamically to property without attribute constructor(Reflection.Emit)

I was able to add Attribute and pass it values by constructor. But how to pass values when Attribute do not have constructor with appropriate parameters to pass. e.g. How to add this DisplayAttribute using Reflection.Emit?

[Display(Order = 28, ResourceType = typeof(CommonResources), Name = "DisplayComment")]

Hope it clear enough what I'm trying to accomplish. If not please ask.

like image 603
Harry89pl Avatar asked Dec 27 '22 00:12

Harry89pl


1 Answers

You use CustomAttributeBuilder. For example:

var cab = new CustomAttributeBuilder(
    ctor, ctorArgs,
    props, propValues,
    fields, fieldValues
);
prop.SetCustomAttribute(cab);

(or one of the related overloads)

In your case, that looks (this is pure guesswork) something like:

var attribType = typeof(DisplayAttribute);
var cab = new CustomAttributeBuilder(
    attribType.GetConstructor(Type.EmptyTypes), // constructor selection
    new object[0], // constructor arguments - none
    new[] { // properties to assign to
        attribType.GetProperty("Order"),
        attribType.GetProperty("ResourceType"),
        attribType.GetProperty("Name"),
    },
    new object[] { // values for property assignment
        28,
        typeof(CommonResources),
        "DisplayComment"
    });
prop.SetCustomAttribute(cab);

Note I'm assuming that Order, ResourceType and Name are properties. If they are fields, there is a different overload.

like image 177
Marc Gravell Avatar answered Apr 30 '23 12:04

Marc Gravell