4

追加Attributeして渡すことができましvaluesconstructor。しかし、渡す適切なパラメータを持っていないvalues場合の渡し方。例これを追加する方法は?AttributeconstructorDisplayAttribute using Reflection.Emit

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

私が達成しようとしていることを十分に明確にしてください。そうでない場合は、お尋ねください。

4

1 に答える 1

10

を使用しますCustomAttributeBuilder。例えば:

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

(または関連するオーバーロードの 1 つ)

あなたの場合、それは次のようになります(これは純粋な推測です):

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プロパティであると仮定していることに注意してください。それらがfieldsの場合、別のオーバーロードがあります。

于 2013-07-15T09:05:11.287 に答える