获取实例方法并调用它
using System;
public class Program
{
public static void Main()
{
var theString = "hello";
var method = theString
.GetType()
.GetMethod("Substring",
new[] {typeof(int), typeof(int)}); //方法参数的类型
var result = method.Invoke(theString, new object[] {0, 4});
Console.WriteLine(result);
}
}输出:
地狱
观看演示
获取静态方法并调用它
另一方面,如果该方法是静态的,则不需要实例来调用它。
var method = typeof(Math).GetMethod("Exp");
var result = method.Invoke(null, new object[] {2});//将null作为第一个参数传递(不需要实例)
Console.WriteLine(result); //你会得到e ^ 2输出:
7.38905609893065
观看演示