1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】リフレクションで静的プロパティにアクセスするのはめんどくさい

Posted at

はじめに

リフレクションを利用して静的プロパティにアクセスしたいときってありますよね?
(publicではないプロパティを触りたいときなど)
ググるとやり方はいくらでも出てきますが,それにもかかわらず実際に書いてみると躓いてしまったので,記事として残しておこうと思います。

やり方

ダラダラ書いてもしょうがないので例を示します。
ここでは,別アセンブリ内の静的クラスQiita.MyClassに定義されているPropの値を取得します。
当然ですが,Qiita.MyClassが定義されているアセンブリが参照に追加されている必要があります。

// using System;
// using System.Reflection;

// 別アセンブリ内のクラスは`Type.GetType`では取得できないので,`Assembly.GetType`を利用する。
Type MyClass;
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())  // 読み込まれているアセンブリを取得
{
  var T = asm.GetType("Qiita.MyClass");  // 目的の型を取得しようとしてみる。

  if (T != null)  // 取得できなかったら`null`になる。
  {
    MyClass = T;
    break;
  }
}

// StaticとNonPublicを両方指定しないといけない。
var info = MyClass.GetProperty("Prop", BindingFlags.Static | BindingFlags.NonPublic);

// ここでも`BindingFlags.Static`が必要。
dynamic val = info.GetValue(MyClass, BindingFlags.Static, null, null, null);

// 取得した`val`で何かする

最後のPropertyInfo.GetValueの呼び出し時にBindingFlags.Staticを渡さないとArgumentExceptionになってしまいます。
これがわからなかったので時間を溶かしてしまいました。
調べても書いてなかったんだもん

PropertyInfo.GetValueの戻り値はobjectですが,dynamicで受けると適当な型として扱えます。怖いですが……。

まとめ

publicではないということには理由があるので,リフレクションで強引にアクセスしようとするのはやめましょう。
(パフォーマンス的にもよろしくない)

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?