C#通过属性反射设置属性值

joh*_*hnc 18 c# reflection

我试图通过类属性上的属性构建一个对象,该属性指定提供的数据行中的列是属性的值,如下所示:

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

    [StoredDataValue("PrograGuid")]
    public string ProgramGuid { get; protected set; }
Run Code Online (Sandbox Code Playgroud)

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

        MemberInfo info = GetType();
        object[] properties = info.GetCustomAttributes(true);
Run Code Online (Sandbox Code Playgroud)

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

首先,我似乎没有找回正确的属性.

现在我有了属性,我如何通过反射设置这些属性?我在做/思考一些根本不正确的事情吗?

Tam*_*ege 39

这里有几个不同的问题

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

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

这里有一个小代码片段可以帮助您开始:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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