クラス内で定義された変数a,b,c
(フィールド)を、for
文で回す方法を書いていきます。
簡単な方法としては、新しく配列に再格納してfor
文で回すなどの方法があるかと思いますが、この場合、変数d
を追加したときに配列にd
を追加し忘れる、といったことが起きる場合があるため、それを防ぐためにも以下のようなコードを実装すべきかと思います。
サンプルコード
今回の説明のために書いたサンプルコードは以下の通りです。
using System.Reflection;
internal class Program
{
private static void Main(string[] args)
{
TestProperties test = new TestProperties()
{
a = "new_a",
b = "new_b",
c = "new_c"
};
// PropertyInfo に個別のプロパティの情報が取得される
foreach (PropertyInfo property in test.GetType().GetProperties())
{
Console.WriteLine("property.Name..." + property.Name);
// インスタンス化した TestProperties を GetValue(~)で指定
Console.WriteLine("value..." + property.GetValue(test));
}
}
/// <summary>
/// for文で回すプロパティを定義したクラス
/// </summary>
internal class TestProperties
{
public string a { get; set; } = "default_a";
public string b { get; set; } = "default_b";
public string c { get; set; } = "default_c";
}
}
↓↓↓↓↓ 実行結果(コンソールの出力) ↓↓↓↓↓
property.Name...a
value...new_a
property.Name...b
value...new_b
property.Name...c
value...new_c
解説
.GetProperties()
によって、メンバー変数(今回の場合はa,b,c
)をPropertyInfo
の配列として取得し、PropertyInfo
の.GetValue()
で変数に格納された値を取得しています。
test.GetType()
ではTestProperties
のType
を取得する処理をしています。
因みに、typeof(TestProperties)
と書いてもtest.GetType()
と同じことができます。
インスタンスの場合は.GetType()
、型定義の場合はtypeof()
を使用するという認識になります。
PropertyInfo.GetValue()
で各変数ごとの値が取得できます。
.GetValue()
の引数にはTestProperties
のインスタンスを入れることで、そのインスタンスの変数を取得することができます。