![](/img/trans.png)
[英]Programmatically Adding new attribute for existing class property with 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);
注意我假設Order
, ResourceType
和Name
是屬性 。 如果它們是字段 ,則存在不同的重載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.