最終更新: bokkuri_orz 2012年05月30日(水) 02:22:59履歴
System.Type.InvokeMember() を利用して、文字列でメソッドを呼び出すことが出来ます。
まずはサンプルクラス。
class Class1 { public void PublicMethod() { Console.WriteLine(">>> PublicMethod"); } public int MethodArgument2(int v1, int v2) { int ret = v1+v2; Console.WriteLine(string.Format(">>> MethodArgument2 : {0} + {1} = {2}",v1,v2,ret)); return ret; } public static void StaticMethod() { Console.WriteLine(">>> StaticMethod"); } private void PrivateMethod() { Console.WriteLine(">>> PrivateMethod"); } }
InvokeMember を使って、それぞれのメソッドを呼び出します。
using System.Reflection; // Class1の型情報 Type type = typeof(Class1); // 型情報からインスタンスを生成 object instance = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, null); // publicメソッド呼び出し type.InvokeMember("PublicMethod", BindingFlags.InvokeMethod, null, instance, null); // 引数、返り値ありのメソッド object ret = type.InvokeMember("MethodArgument2", BindingFlags.InvokeMethod, null, instance, new object[] { 1, 2 }); Console.WriteLine(" return value : " + ret); // staticメソッド呼び出し type.InvokeMember("StaticMethod", BindingFlags.InvokeMethod, null, null, null); // privateメソッド呼び出し // ※通常は外部から呼び出せない privateメソッドまで呼び出せる。 type.InvokeMember("PrivateMethod", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, instance, null);
実行結果
>>> PublicMethod >>> MethodArgument2 : 1 + 2 = 3 return value : 3 >>> StaticMethod >>> PrivateMethod
他にも、プロパティの取得、設定、インデクサ等、全てのアクセスができます。
System.Type.GetMethods() を利用して、メソッドの情報を調べることが出来ます。
上記クラス Class1 を使ったサンプルコード。
Type type = typeof(Class1); MethodInfo[] methodInfo = type.GetMethods(); foreach (MethodInfo mi in methodInfo) { Console.WriteLine(string.Format("{0} : ret {1}", mi.Name, mi.ReturnType.ToString())); // メソッド名と返り値の型 if (mi.IsStatic) Console.WriteLine(" static"); if (mi.IsPublic) Console.WriteLine(" public"); if (mi.IsPrivate) Console.WriteLine(" private"); }
実行結果
ベースクラスの ToString, Equals, GetHashCode, GetType も出力されています。
PublicMethod : ret System.Void public MethodArgument2 : ret System.Int32 public StaticMethod : ret System.Void static public ToString : ret System.String public Equals : ret System.Boolean public GetHashCode : ret System.Int32 public GetType : ret System.Type public
同様に、
System.Type.GetMembers、System.Type.GetInterfaces、System.Type.GetProperties など、クラスに関する情報は全て調べることができます。
タグ
最新コメント