C# 將字符串轉為函數名


 

class Program

{

  static void Main(string[] args)

  {

    Type t = typeof(Program);//參數為所要使用的函數所在的類的類名。

    MethodInfo mt = t.GetMethod("foo");

    if (mt == null)

    {

      Console.WriteLine("沒有獲取到相應的函數!!");

    }

    else

    {

      string str = (string)mt.Invoke(null,new object[] { "1234567890" });

     }

    Console.ReadKey();

   }

 

  private static string foo(string abc)

  {

    return abc;

  }

}

 

來源:https://blog.csdn.net/realDonaldTrump/article/details/79664926

 

附【僅參考用】:

Type t = typeof(controlServerBll);//括號中的為所要使用的函數所在的類的類名。
Dictionary<string, object> dataDic = JsonUtil.ToDictionary(data);
string controlFunc = "";
if (dataDic["controlType"].ToString() == "1")
{
controlFunc = "OpenServer";
}
else if (dataDic["controlType"].ToString() == "2")
{
controlFunc = "StopServer";
}
else if (dataDic["controlType"].ToString() == "3")
{
controlFunc = "RestartServer";
}
MethodInfo mt = t.GetMethod(controlFunc, BindingFlags.Default);
responseData = (string)mt.Invoke(null, new object[] { serverName });

LogHelper<ClassName>.Debug(responseData);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM