LoginSignup
8
9

More than 5 years have passed since last update.

リフレクションで静的クラスのプロパティを取得

Posted at

例えば、

Hoge.cs
public static class Hoge
{
  static string hoge1 = "hogeabc";
  public static string Hoge1 { get { return hoge1; } }

  static string hoge2 = "hogeaac";
  public static string Hoge2 { get { return hoge2; } }

  static string hoge3 = "hogeagq";
  public static string Hoge3 { get { return hoge3; } }
}

という静的クラスがあって、Hogeクラスに定義されているプロパティ全てにアクセスしたい場合、

Reflection.cs
static void Main(string[] args)
{
  var hogeType = typeof(Hoge);
  var names = hogeType.GetProperties(BindingFlags.Static|BindingFlags.Public)
              .Where(x => x.PropertyType == typeof(string))
              .Select(x => x.GetValue(hogeType, null) as string).ToList();
  foreach (var item in names)
  {
    Console.WriteLine(item);
  }
}

とすればstaticでpublicなstring型のプロパティ全てにアクセスできます。

ちなみに、PropertyInfo#GetValue(object obj, object[] index)の第一引数は
取得するオブジェクトのインスタンスです。(静的プロパティの場合はそのクラスのTypeオブジェクト)

8
9
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
8
9