C# 将字符串转换为函数:执行代码中的函数或事件
我被困在一个点上,我想要一个字符串来执行我代码中的函数或事件。例如,如果C# 将字符串转换为函数:执行代码中的函数或事件,c#,string,C#,String,我被困在一个点上,我想要一个字符串来执行我代码中的函数或事件。例如,如果 string somestr = "fun"; 我想执行一个名为fun的函数 public bool fun() { return true; } 我可以操纵somestr来执行fun或fun之类的操作 到目前为止,我所能想到的最好的方法是创建一个事件或函数,在这里我应该检查并比较switch case中的字符串,然后执行函数或引发事件,如 public void ReceivedCommand() {
string somestr = "fun";
我想执行一个名为fun的函数
public bool fun()
{
return true;
}
我可以操纵somestr来执行fun或fun之类的操作
到目前为止,我所能想到的最好的方法是创建一个事件或函数,在这里我应该检查并比较switch case中的字符串,然后执行函数或引发事件,如
public void ReceivedCommand()
{
if(somestr == "fun")
{
bool b = fun();
}
else if(somestr == "Otherfun")
{
//Some Other Function
}
}
但现在的情况是,我有几百个函数和很少的事件,用户可以选择其中任何一个。我非常确信,应该有一些东西能够以一种简单的方式解决我的问题,而不是编写大量的ifs和switch
你能给我指出正确的方向吗?我应该如何做到这一点。你可以使用Type.getMethodName使用反射来获得你想要的方法,它的名称就是Type.getMethodName。
请参见使用反射。大概是这样的:
Type type = this.GetType();
MethodInfo methodInfo = type.GetMethod(somestr);
methodInfo.Invoke(this, userParameters);
// And this requires "using System.Reflection;"
或
尝试链接,我希望它能工作您可以像这样动态地完成它
class MethodInvoker
{
delegate void TestDelegate();
public void fun()
{
Console.WriteLine("fun");
}
public void InvokeFromString(string functionName)
{
TestDelegate tDel = () => { this.GetType().GetMethod(functionName).Invoke(this, null); };
tDel.Invoke();
}
}
像这样使用它
var test = new MethodInvoker();
test.InvokeFromString("fun");
看看这个吧,谢谢你的时间。我来看看,让我试试这个。我确信它会起作用的你确定吗?让我试一试。但它似乎不起作用。它起作用了,检查一下这不是一个Javascript问题。看看标签。y,我看到了:使用这个链接-