C# 循环遍历对象并获取属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15586123/
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
loop through object and get properties
提问by user1438082
i have a method that returns a list of operating system properties. Id like to loop through the properties and do some processing on each one.All properties are strings
我有一个返回操作系统属性列表的方法。我想遍历属性并对每个属性进行一些处理。所有属性都是字符串
How do i loop through the object
我如何循环遍历对象
C#
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;
//......
}
采纳答案by dasblinkenlight
You can do it with reflection:
你可以用反射来做到:
// 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);
...
}
[EDIT by Matthew Watson] I've taken the liberty of adding a further code sample, based on the code above.
[由Matthew Watson编辑] 基于上面的代码,我冒昧地添加了一个进一步的代码示例。
You could generalise the solution by writing a method that will return an IEnumerable<string>
for any object type:
您可以通过编写一个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));
}
And you can generalise it even further with generics:
你可以用泛型进一步概括它:
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));
}
Using this second form, to iterate over all the string properties of an object you could do:
使用第二种形式,遍历对象的所有字符串属性,您可以执行以下操作:
foreach (var property in PropertiesOfType<string>(myObject)) {
var name = property.Key;
var val = property.Value;
...
}
回答by Muhammad Omar ElShourbagy
You can use Reflection to loop the GetProperties
Resullt:
您可以使用反射来循环GetProperties
结果:
OS_Result.OSResultStruct.GetType().GetProperties()