遍历所有类属性

本文关键字:属性 遍历 | 更新日期: 2023-09-27 18:15:27

也许相当简单的问题,但我有一个初始化的类对象,通过参数传递给另一个类。然后读取类对象以检查其成员的值,如果不正确则可能修改它们。

我可以访问单个属性并更改它们的值,但我想做的是循环遍历所有整数类型属性以检查它们的基值并在必要时更改它。

下面是对象结构的一个例子:
+ Prices
++ MainPrices
+++ RelevantPrices
++++ (Int) Price
+ SubPrices
++ MainPrices
+++ RelevantPrices
++++ (Int) Price
+Rooms
++ Data
+++ (String) Name
+++ (Int) NameType
+++ (String) Location
+++ (Int) RoomNumber

我这里需要做的是得到房间。数据和循环遍历其所有Int类型参数。我已经尝试使用反射,但我需要一个新的实例引用的类型,我所有的是初始化的类对象在这里。

谁能建议什么可能是最好的方式来循环和有条件地改变他们现有的值,请?

编辑:

下面是一些示例代码:
public class Test()
{
public Void Init(MyClassObject Data)
{
//Data is initialised with data, it has the structure explained in the original description
//What i need to do is loop over the initialised objects properties here in this Init method,
}
}

遍历所有类属性

这将给你一个整数属性列表

var integers = this.GetType().GetProperties().Where(p => p.PropertyType == typeof(int)).ToList();