繁体   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