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;
    //......

}
4

2 に答える 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));
}

この2番目の形式を使用して、オブジェクトのすべての文字列プロパティを反復処理するには、次のようにします。

foreach (var property in PropertiesOfType<string>(myObject)) {
    var name = property.Key;
    var val = property.Value;
    ...
}
于 2013-03-23T11:23:13.827 に答える
2

Reflectionを使用して、結果をループできますGetProperties

OS_Result.OSResultStruct.GetType().GetProperties()
于 2013-03-23T11:21:34.590 に答える