あなたは反射でそれを行うことができます:
// 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));
}
この2番目の形式を使用して、オブジェクトのすべての文字列プロパティを反復処理するには、次のようにします。
foreach (var property in PropertiesOfType<string>(myObject)) {
var name = property.Key;
var val = property.Value;
...
}