0
0

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.

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

Posted at

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#のリフレクションについて、思いつくままにコードを書く

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?