迭代所有类属性

时间:2016-10-27 15:30:44

标签: c# reflection

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

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

以下是对象结构的示例:

+ Prices
++ MainPrices
+++ RelevantPrices
++++ (Int) Price

+ SubPrices
++ MainPrices
+++ RelevantPrices
++++ (Int) Price

+Rooms
++ Data
+++ (String) Name
+++ (Int) NameType
+++ (String) Location
+++ (Int) RoomNumber

我需要做的是获取Rooms.Data并遍历其所有的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,
}

}

1 个答案:

答案 0 :(得分:0)

这将为您提供整数属性列表

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