.Net反射-MethodInfo
Main方法:
static async Task Main(string[] args)
{
Type personType = typeof(Person);
var person = Activator.CreateInstance(personType);
//调用同步方法,如果有同名方法,必须带方法参数Type数组
object returnValue1 = personType.GetMethod("Say", new Type[] { }).Invoke(person, new object[] { });//hi
//调用同步带参数方法
object returnValue2 = personType.GetMethod("Say", new Type[] { typeof(string) }).Invoke(person, new object[] { "fan" });//hi,fan
//调用异步方法
var asyncMethod = personType.GetMethod("SayAsync", new Type[] { });
var task = asyncMethod.Invoke(person, new object[] { }) as Task;
await task;
object result = task.GetType().GetProperty("Result").GetValue(task, null); //async hi
//获取方法参数列表
ParameterInfo[] paras=asyncMethod.GetParameters();
}
Person类:
public class Person
{
public string Say()
{
return "async hi";
}
public string Say(string name)
{
return "hi," + name;
}
public async Task<string> SayAsync()
{
var result = await Task.Run<string>(() => "async hi");
return result;
}
}