C#通过与反射属性设置属性值 [英] C# setting property values through reflection with attributes
问题描述
我试图通过指定所提供的数据行一列,它是该属性的值,如下一类属性的属性建立一个对象:
I am trying to build an object through an attribute on a classes property that specifies a column in a supplied data row that is the value of the property, as below:
[StoredDataValue("guid")]
public string Guid { get; protected set; }
[StoredDataValue("PrograGuid")]
public string ProgramGuid { get; protected set; }
在一个基础对象建立()方法中,我得到的属性值设置这些属性
In a Build() method on a base object, I am getting the attribute values set on these properties as
MemberInfo info = GetType();
object[] properties = info.GetCustomAttributes(true);
不过,在这一点上,我意识到在我的知识的局限性。
However, at this point I am realising the limitation in my knowledge.
一开始,我似乎并没有被找回正确的属性。
For a start, I don't appear to be getting back the correct attributes.
和如何设置通过反思这些属性,现在我有属性?我做/想的东西根本不正确?
And how do I set these properties through reflection, now that I have the attributes? Am I doing / thinking something fundamentally incorrect?
推荐答案
有一对夫妇在这里不同的问题。
There are a couple of separate issues here
-
的typeof(MyClass的).GetCustomAttributes(布尔)
(或的GetType() .GetCustomAttributes(布尔)
)返回类本身,而不是成员的属性的属性。你将不得不调用的typeof(MyClass的).GetProperties()
来得到在类属性的列表,然后检查他们每个人。
typeof(MyClass).GetCustomAttributes(bool)
(orGetType().GetCustomAttributes(bool)
) returns the attributes on the class itself, not the attributes on members. You will have to invoketypeof(MyClass).GetProperties()
to get a list of properties in the class, and then check each of them.
一旦你得到的财产,我认为你应该使用 Attribute.GetCustomAttribute()
而不是的MemberInfo。 GetGustomAttributes()
,因为你确切地知道什么属性,你所寻找的。 p>
Once you got the property, I think you should use Attribute.GetCustomAttribute()
instead of MemberInfo.GetGustomAttributes()
since you exactly know what attribute you are looking for.
下面是一个小的代码片段,以帮助您开始:
Here's a little code snippet to help you start:
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)
来获得其他种类的属性以及
EDIT: Don't forget that Type.GetProperties()
only returns public properties by default. You will have to use Type.GetProperties(BindingFlags)
to get other sorts of properties as well.
这篇关于C#通过与反射属性设置属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!