首页 >后端开发 >C++ >C# 可以使用反射从字符串调用函数吗?

C# 可以使用反射从字符串调用函数吗?

Patricia Arquette
Patricia Arquette原创
2025-01-26 02:26:09887浏览

Can C# Call a Function from a String Using Reflection?

C# 中通过字符串调用函数

PHP 可以通过字符串调用函数,如下所示:

<code class="language-php">$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }</code>

.Net 是否可以实现类似的功能?

答案:

是的,.Net 可以使用反射通过字符串调用函数。以下是实现方法:

<code class="language-csharp">Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);</code>

上述代码中,调用的方法必须具有公共访问修饰符。如果需要调用非公共方法,可以使用 BindingFlags 参数,如下所示:

<code class="language-csharp">Type thisType = this.GetType();
MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);</code>

以上是C# 可以使用反射从字符串调用函数吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn