我有 1000 個方法,稱為 method0001、method0002、...、method1000。 我有一個取值在 1 到 1000 之間的變量。如果變量的值為x,我想調用methodx。例如,如果變量的值為 34,我想調用 method0034。請問我該如何用 C# 編寫這個代碼?很多人都在問 Methodwxyz 需要什么。每種方法都是不同類型的數學問題。我已經按照有用的評論完成了此操作,但收到錯誤(編輯了之前的問題) using System.Collections.Generic; using UnityEngine; public class TextControl : MonoBehaviour{public static TextControl instance;void Start(){ instance = this;}// Update is called once per framevoid Update(){ this.GetType().GetMethod("Template00" + "1").Invoke(this, null);}public static string Templates001(){ // doing something here} } 謝謝
1 回答

紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
你可以通過反思來做到這一點。編輯快速示例(忘記調用參數)。關于反射的一些提示:
如果出現 nullException 則意味著找不到該方法
您調用的方法需要公開
如果您使用混淆,您的方法可能不會具有相同的名稱
代碼
public class Program
{
public static void Main(string[] args)
{
Check method1 = new Check(1);
Check method2 = new Check(2);
}
}
public class Check
{
public Check(int x)
{
this.GetType().GetMethod("Method" + x).Invoke(this, null);
}
public void Method1()
{
Console.WriteLine("Method 1");
}
public void Method2()
{
Console.WriteLine("Method 2");
}
}
- 1 回答
- 0 關注
- 193 瀏覽
添加回答
舉報
0/150
提交
取消