C# 反射调用重载方法

准备一个类

 1 public class MethodCLass
 2     {
 3         public void Method()
 4         {
 5             Console.WriteLine($"无参方法");
 6             return;
 7         }
 8 
 9         public void Method(int arg)
10         {
11             Console.WriteLine($"整数类型的方法-{arg}");
12         }
13 
14         public void Method(string arg)
15         {
16             Console.WriteLine($"字符串类型的方法-{arg}");
17         }
18 
19         public void Method(string arg1, int arg2)
20         {
21             Console.WriteLine($"两个参数的方法-{arg1}=={arg2}");
22         }
23     }

准备一个方法

1 private static void InvokeMethod<T>(object obj, T arg)
2         {
3             var method = obj.GetType().GetMethod("Method", new Type[] { typeof(T) });
4             method.Invoke(obj, new object[] { arg });
5         }

运行

1 private static void Main(string[] args)
2         {
3             var obj = Activator.CreateInstance(typeof(MethodClass));
4 
5             InvokeMethod(obj, "xxhh");
6             InvokeMethod(obj, 123);
7         }

 

运行结果

字符串类型的方法-xxhh
整数类型的方法-123

 

posted @ 2021-07-12 19:47  只吃肉不喝酒  阅读(803)  评论(1编辑  收藏  举报