如何在没有属性构造函数的情况下向属性添加动态添加的属性值(Reflection.Emit)

时间:2013-07-15 08:56:39

标签: c# reflection attributes reflection.emit

我能够添加Attribute并将values传递给constructor。 但是,当values没有Attribute并且有适当的参数要通过时,如何传递constructor。 例如如何添加此DisplayAttribute using Reflection.Emit

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

希望我能够清楚地完成我想要完成的任务。 如果没有,请问。

1 个答案:

答案 0 :(得分:9)

您使用CustomAttributeBuilder。例如:

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

(或其中一个相关的重载)

在你的情况下,看起来(这是纯粹的猜测)类似于:

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);

注意我假设OrderResourceTypeName属性。如果它们是字段,则存在不同的重载。