簡體   English   中英

如何在沒有屬性構造函數的情況下向屬性添加動態添加的屬性值(Reflection.Emit)

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

我能夠添加Attribute並通過constructor傳遞它的values 但是當Attribute沒有具有適當參數的constructor傳遞時,如何傳遞values 例如,如何using Reflection.Emit添加此DisplayAttribute

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

希望我能夠清楚地完成我想要完成的任務。 如果沒有,請問。

您使用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屬性 如果它們是字段 ,則存在不同的重載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM