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

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

DDD
发布: 2025-01-26 02:09:08
原创
376 人浏览过

Can C# Call a Function from a String?

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

PHP 可以通过存储在字符串中的函数名来调用函数。例如:

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

function hello() { echo 'hello'; }</code>
登录后复制

.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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板