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

StackOverflow https://stackoverflow.com/questions/17650302

سؤال

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top