我有一个字符串,需要将此字符串转换为代码。
string s = "Method1";
string s_1 = "()";
s = s + s_1;
switch ((irrelevant))
{
case 1:
(i need the string to code here to enable the Mehod1)
break;
}
void Method1()
{
}
有没有办法做到这一点?
答案 0 :(得分:1)
使用反射,您可以通过名称(名称不带括号)调用方法,只需使用名称。
如果您需要按名称执行方法
,则必须接受此解决方案示例,如果您的方法在名为Method1
ClassWithMethods
Type type = typeof(ClassWithMethods);
MethodInfo methodInfo = type.GetMethod("Method1");
result = methodInfo.Invoke(this, null);
调用的第一个参数我使用它,因为它运行相同的intance但是这个参数要求调用方法或构造函数的对象。如果方法是静态的,则忽略此参数。如果构造函数是静态的,则此参数必须为null或定义构造函数的类的实例