循环遍历对象并获取属性

时间:2013-03-23 11:18:12

标签: c# object

我有一个返回操作系统属性列表的方法。我想循环遍历属性并对每个属性进行一些处理。所有属性都是字符串

如何遍历对象

C#

// test1 and test2 so you can see a simple example of the properties - although these are not part of the question
String test1 = OS_Result.OSResultStruct.OSBuild;
String test2 = OS_Result.OSResultStruct.OSMajor;

// here is what i would like to be able to do
foreach (string s in OS_Result.OSResultStruct)
{
    // get the string and do some work....
    string test = s;
    //......

}

2 个答案:

答案 0 :(得分:11)

您可以使用反射

来完成
// Obtain a list of properties of string type
var stringProps = OS_Result
    .OSResultStruct
    .GetType()
    .GetProperties()
    .Where(p => p.PropertyType == typeof(string));
foreach (var prop in stringProps) {
    // Use the PropertyInfo object to extract the corresponding value
    // from the OS_Result.OSResultStruct object
    string val = (string)prop.GetValue(OS_Result.OSResultStruct);
    ...
}

[编辑Matthew Watson] 我已经冒昧地根据上面的代码添加了另一个代码示例。

您可以通过编写一个为任何对象类型返回IEnumerable<string>的方法来概括解决方案:

public static IEnumerable<KeyValuePair<string,string>> StringProperties(object obj)
{
    return from p in obj.GetType().GetProperties()
            where p.PropertyType == typeof(string)
            select new KeyValuePair<string,string>(p.Name, (string)p.GetValue(obj));
}

你可以用泛型进一步概括它:

public static IEnumerable<KeyValuePair<string,T>> PropertiesOfType<T>(object obj)
{
    return from p in obj.GetType().GetProperties()
            where p.PropertyType == typeof(T)
            select new KeyValuePair<string,T>(p.Name, (T)p.GetValue(obj));
}

使用第二种形式,迭代你可以做的对象的所有字符串属性:

foreach (var property in PropertiesOfType<string>(myObject)) {
    var name = property.Key;
    var val = property.Value;
    ...
}

答案 1 :(得分:1)

您可以使用Reflection来循环GetProperties Resullt:

OS_Result.OSResultStruct.GetType().GetProperties()