獲取方法並呼叫它

獲取 Instance 方法並呼叫它

using System;
                
public class Program
{
    public static void Main()
    {
        var theString = "hello";
        var method = theString
                     .GetType()
                     .GetMethod("Substring",
                                new[] {typeof(int), typeof(int)}); //The types of the method arguments
         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});//Pass null as the first argument (no need for an instance)
Console.WriteLine(result); //You'll get e^2

輸出:

7.38905609893065

檢視演示