LoginSignup
0
0

More than 1 year has passed since last update.

【C#】メンバー変数`a,b,c`を for 文で回す

Last updated at Posted at 2022-12-02

クラス内で定義された変数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()ではTestPropertiesTypeを取得する処理をしています。
因みに、typeof(TestProperties)と書いてもtest.GetType()と同じことができます。
インスタンスの場合は.GetType()、型定義の場合はtypeof()を使用するという認識になります。

PropertyInfo.GetValue()で各変数ごとの値が取得できます。
.GetValue()の引数にはTestPropertiesのインスタンスを入れることで、そのインスタンスの変数を取得することができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0