在 C# 中从字符串调用函数 [英] Calling a function from a string in C#
本文介绍了在 C# 中从字符串调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在 php 中你可以拨打这样的电话:
I know in php you are able to make a call like:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
这在 .Net 中可行吗?
Is this possible in .Net?
推荐答案
是的.您可以使用反射.像这样:
Yes. You can use reflection. Something like this:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
以上代码中,调用的方法必须有访问修饰符public
.如果调用非公共方法,则需要使用 BindingFlags
参数,例如BindingFlags.NonPublic |BindingFlags.Instance
:
With the above code, the method which is invoked must have access modifier public
. If calling a non-public method, one needs to use the BindingFlags
parameter, e.g. BindingFlags.NonPublic | BindingFlags.Instance
:
Type thisType = this.GetType();
MethodInfo theMethod = thisType
.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);
这篇关于在 C# 中从字符串调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文