我能够添加Attribute
并将values
传递给constructor
。
但是,当values
没有Attribute
并且有适当的参数要通过时,如何传递constructor
。
例如如何添加此DisplayAttribute
using
Reflection.Emit
?
[Display(Order = 28, ResourceType = typeof(CommonResources), Name = "DisplayComment")]
希望我能够清楚地完成我想要完成的任务。 如果没有,请问。
答案 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);
注意我假设Order
,ResourceType
和Name
是属性。如果它们是字段,则存在不同的重载。