【问题标题】:C# setting property values through reflection with attributesC#通过属性反射设置属性值
【发布时间】:2008-12-24 01:43:04
【问题描述】:

我正在尝试通过 classes 属性上的属性构建对象,该属性指定提供的数据行中作为属性值的列,如下所示:

    [StoredDataValue("guid")]
    public string Guid { get; protected set; }

    [StoredDataValue("PrograGuid")]
    public string ProgramGuid { get; protected set; }

在基础对象的 Build() 方法中,我将这些属性上设置的属性值设置为

        MemberInfo info = GetType();
        object[] properties = info.GetCustomAttributes(true);

但是,在这一点上,我意识到我的知识有限。

首先,我似乎没有恢复正确的属性。

既然有了属性,我该如何通过反射来设置这些属性?我在做/想什么根本不正确的事情吗?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    这里有几个单独的问题

    • typeof(MyClass).GetCustomAttributes(bool)(或GetType().GetCustomAttributes(bool))返回类本身的属性,而不是成员的属性。您必须调用 typeof(MyClass).GetProperties() 来获取类中的属性列表,然后检查每个属性。

    • 一旦你得到了这个属性,我认为你应该使用Attribute.GetCustomAttribute()而不是MemberInfo.GetGustomAttributes(),因为你确切地知道你在寻找什么属性。

    这里有一个小代码 sn-p 来帮助你开始:

    PropertyInfo[] properties = typeof(MyClass).GetProperties();
    foreach(PropertyInfo property in properties)
    {
        StoredDataValueAttribute attribute =
            Attribute.GetCustomAttribute(property, typeof(StoredDataValueAttribute)) as StoredDataValueAttribute;
    
        if (attribute != null) // This property has a StoredDataValueAttribute
        {
             property.SetValue(instanceOfMyClass, attribute.DataValue, null); // null means no indexes
        }
    }
    

    编辑:不要忘记Type.GetProperties() 默认只返回公共属性。您还必须使用Type.GetProperties(BindingFlags) 来获取其他类型的属性。

    【讨论】:

    • 我会做一个测试并告诉你,虽然看起来合乎逻辑
    • Attribute.GetCustomAttribute(...) 返回一个 System.Attribute 数组,不能简单地转换为属性本身。显示的示例甚至无法编译,更不用说工作了。您需要测试数组长度以查看是否存在所需的属性并将第一个元素转换为所需的类型。
    • 该示例使用 GetCustomAttribute,而不是 GetCustomAttributes。该示例在我尝试时编译(当然,更改属性名称)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多