迭代类属性

时间:2009-02-21 02:30:16

标签: c# properties iteration

我正在尝试迭代Color类的Color属性。

不幸的是它不在集合中,所以它只是一个带有一堆静态属性的类。

有没有人知道它是否可以迭代一个类'属性是静态的还是基于对象的?

2 个答案:

答案 0 :(得分:29)

是的,可以使用反射。特定颜色定义为Color struct的静态属性。

 PropertyInfo[] colors = typeof(Color).GetProperties(BindingFlags.Static|BindingFlags.Public);
 foreach(PropertyInfo pi in colors) {
     Color c = (Color)pi.GetValue(null, null);
     // do something here with the color
 }

答案 1 :(得分:2)

您可能也对此代码感兴趣

http://blog.guymahieu.com/2006/07/11/deep-reflection-of-properties-propertyreflector/

它提供了一种按名称设置/获取属性的简便方法。如果您查看GetBestMatchingProperty,您将找到对属性的迭代,这与之前发布的方式相同 Iterating over class properties

相关问题