循环遍历对象并获取属性

10
我有一个返回操作系统属性列表的方法。我希望循环遍历每个属性并进行一些处理。所有属性都是字符串类型。
如何循环遍历该对象? 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个回答

14

你可以使用 反射 来完成:

// 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
@user1438082 看起来你正在使用 .NET 4.0 或更早版本;那么请尝试使用旧版本的 GetValue(OS_Result.OSResultStruct, null) - Sergey Kalinichenko
1
@user1438082 那就是 prop.Name 了。 - Sergey Kalinichenko
1
不错的代码片段。我会把它复制一份,谢谢。hoick ;) - Matthew Watson
2
@MatthewWatson 感谢您的编辑!我将输出更改为 IEnumerable<KeyValuePair<string,T>>,以便使用您方法的用户可以访问属性名称,而不仅仅是属性值。 - Sergey Kalinichenko
1
那就更好了! :) - Matthew Watson
显示剩余2条评论

2
您可以使用反射来循环遍历 GetProperties 的结果:
OS_Result.OSResultStruct.GetType().GetProperties()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接