文字列からstatic/classプロパティの取得
staticプロパティを文字列から取得する方法がわからなかったので調べてみた。
ついでに、文字列でオブジェクトのプロパティの取り出しとメソッドの実行も。
class TestClass {
public static string StaticPropName = "StaticValue";
public int propName = 100;
public string TestFunc(int num) {
return "TestFuncValue : " + num;
}
}
TestClass test = new TestClass();
Type testType = test.GetType();
print(testType.GetField("propName").GetValue(test));
// 出力 : 100
print(testType.GetMethod("TestFunc").Invoke(test, new object[]{ 777 }));
// 出力 : TestFuncValue : 777
Type typeOfTestClass = typeof(TestClass);
print(typeOfTestClass.GetField("StaticPropName").GetValue(typeOfTestClass));
// 出力 : StaticValue
コメントを残す