Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从字符串中调用void_C#_String_Call_Void - Fatal编程技术网

C# 从字符串中调用void

C# 从字符串中调用void,c#,string,call,void,C#,String,Call,Void,我的应用程序正在运行时为字符串定义方法名。我想从字符串中调用该方法 范例 private void ButtonClick(){ string goVoid; goVoid = "testVoid"; goVoid(); // Calling testVoid } testVoid(){ //code } 不能通过简单的方式单独指定字符串名来调用方法,只能通过使用反射来实现。 其他方法不会是动态的,可能是一个开关流控制,它将根据匹配调用所需的方法 对于以下内容

我的应用程序正在运行时为字符串定义方法名。我想从字符串中调用该方法

范例

private void ButtonClick(){
    string goVoid;
    goVoid = "testVoid";
    goVoid(); // Calling testVoid
}

testVoid(){
    //code
}

不能通过简单的方式单独指定字符串名来调用方法,只能通过使用反射来实现。 其他方法不会是动态的,可能是一个开关流控制,它将根据匹配调用所需的方法

对于以下内容,您需要
System.Reflection

string methodName = "testVoid";
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(this, null);

来源:

您不能通过以普通的直接方式单独指定字符串名称来调用方法,只能通过使用反射来实现。 其他方法不会是动态的,可能是一个开关流控制,它将根据匹配调用所需的方法

对于以下内容,您需要
System.Reflection

string methodName = "testVoid";
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(methodName);
theMethod.Invoke(this, null);

来源:

我的直觉告诉我你想做些什么,呃。。。在这里。。。如果必须的话,你可以通过使用反射来做到这一点,但是也许你应该解释一下你需要这样做的真正原因。请阅读。看一看。。但我会首先考虑其他方法来为你的应用程序建模。@Lucastzesniewski,我应该删除我的答案并将其作为副本发布吗?@OrelEraki好吧,谜团重复了这个问题(反正我自己也在做这件事)。我会说,别管它,你给代码赋予适当的属性,这样它的存在就不会有害。我的直觉告诉我,你在试图做一些事,呃。。。在这里。。。如果必须的话,你可以通过使用反射来做到这一点,但是也许你应该解释一下你需要这样做的真正原因。请阅读。看一看。。但我会首先考虑其他方法来为你的应用程序建模。@Lucastzesniewski,我应该删除我的答案并将其作为副本发布吗?@OrelEraki好吧,谜团重复了这个问题(反正我自己也在做这件事)。我要说的是,离开它,您为代码提供了正确的属性,这样它的存在就不会有害。OP可能需要使用绑定标志
BindingFlags.NonPublic | BindingFlags.Instance
如果
testVoid
private
。他的代码在这方面不是很清楚。你是对的,我不想让事情过于复杂,我仍然在想是否要删除我的答案并将其标记为重复。OP可能需要使用绑定标志
bindingsflags.NonPublic | bindingsflags.Instance
if
testVoid
is
private
。他的代码在这方面不是很清楚。你是对的,我不想把事情搞得太复杂,我还在想是否要删除我的答案并将其标记为重复。