【问题标题】:Iterating over class properties迭代类属性
【发布时间】:2009-02-21 02:30:16
【问题描述】:

我正在尝试遍历 Color 类的 Color 属性。

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

有谁知道是否可以迭代一个类的属性,无论是静态的还是基于对象的?

【问题讨论】:

    标签: c# properties iteration


    【解决方案1】:

    是的,可以使用反射。具体颜色被定义为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
     }
    

    【讨论】:

    • 我会添加:if (pi.PropertyType == typeof(Color)) 以防止任何新属性被添加到 Color。
    【解决方案2】:

    您可能也对此代码感兴趣

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

    它提供了一种按名称设置/获取属性的简单方法。如果您查看 GetBestMatchingProperty,您会发现对属性的迭代,其完成方式与之前发布的相同 Iterating over class properties

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-30
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多