- 根据方法名获取方法
- 重载方法的获取
- 重载方法的执行
- 静态方法与实例方法的执行区别
using System;
using System.Reflection;
namespace DynimicExecutionMethod
{
class Program
{
static void Main(string[] args)
{
Type type = typeof(User)
MethodInfo set_Name = type.GetMethod("set_Name");
MethodInfo get_Name = type.GetMethod("get_Name");
MethodInfo say = type.GetMethod("Say",new Type[] {});
MethodInfo say_Msg = type.GetMethod("Say", new Type[] { typeof(string)});
MethodInfo add = type.GetMethod("Add");
MethodInfo print = type.GetMethod("Print");
var user = new User();
Console.WriteLine(get_Name.Invoke(user,null));
set_Name.Invoke(user, new object[] { "张三" });
Console.WriteLine(get_Name.Invoke(user, null));
say.Invoke(user, null);
say_Msg.Invoke(user, new object[] {"你好"});
var result = (int)add.Invoke(user, new object[] {1, 2});
Console.WriteLine(result);
print.Invoke(null, null);
Console.ReadKey();
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public void Say()
{
Console.WriteLine("Hello");
}
public void Say(string msg)
{
Console.WriteLine(msg);
}
public int Add(int a, int b)
{
return a + b;
}
public static void Print()
{
Console.WriteLine("static print method");
}
}
}