你可以用反射来做到这一点:
// 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;
...
}