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);

 

posted @ 2019-09-28 15:48  剑存古风  阅读(1955)  评论(0编辑  收藏  举报