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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With