Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9707

Reflection オーバーロードされているメソッドの呼び出し --メモ--

$
0
0
Reflectionでメソッドを呼び出したい。 StringクラスのRemoveメソッド呼び出し 引数に(int,int)タイプのものを使う。 string str = "HelloWorld"; Type type = str.GetType(); MethodInfo mi1 = type.GetMethod("Remove",new Type[] { typeof(int), typeof(int) }); Console.WriteLine(mi1.Invoke(str, new object[] { 0, 5 })); GetMethodsのリストから該当するメソッドを選択 GetMethodsでStringクラスのメソッドをすべて呼び出す。 そのうちRemoveメソッドを名前で選択。さらに引数が2つのものを選択 string str = "HelloWorld"; Type type = str.GetType(); MethodInfo[] methodInfos = type.GetMethods(); foreach (var mi in methodInfos) if (mi.Name == "Remove") { ParameterInfo[] pi = mi.GetParameters(); if (pi.Length == 2) { Console.WriteLine(mi.Invoke(str, new object[] { 0, 5 })); } }; 参考 文字列で指定したメソッドを呼び出すサンプル・プログラム C#のリフレクションについて、思いつくままにコードを書く

Viewing all articles
Browse latest Browse all 9707

Trending Articles