![](/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.