迭代类属性

Vin*_*cio 17 c# iteration properties

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

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

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

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

  • 我会添加:if(pi.PropertyType == typeof(Color))以防止将来添加到Color的任何新属性. (6认同)