从 C# 中的字符串调用函数 [英] Calling a function from a string in C#

查看:27
本文介绍了从 C# 中的字符串调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I know in php you are able to make a call like:

$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

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);

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆