C#通过属性reflection设置属性值

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

[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); 

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

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

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

这里有几个不同的问题

  • 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 } } 

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