C# 迭代类属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/571982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:44:07  来源:igfitidea点击:

Iterating over class properties

c#propertiesiteration

提问by Vince Panuccio

I'm trying to iterate over the Color class' Color properties.

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

Unfortunately its not in a collection so its just a class with a bunch of static properties.

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

Does anyone know if its possible to iterate over a class' properties be it static or object based?

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

采纳答案by arul

Yes, it's possible using reflection. Specific colors are defined as a static properties of the Color struct.

是的,可以使用反射。特定颜色被定义为 的静态属性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
 }

回答by Bogdan Kanivets

You might also be interested in this code

您可能也对此代码感兴趣

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

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

It provides an easy way to set/get properties by name. If you look into GetBestMatchingProperty you'll find the iteration over properties, that is done the same way as been posted before Iterating over class properties

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