gpt4 book ai didi

c# - 从 C# 中的字符串调用函数

转载 作者:IT老高 更新时间:2023-10-28 11:44:50 26 4
gpt4 key购买 nike

我知道在 php 中你可以这样调用:

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

function hello() { echo 'hello'; }

这在 .Net 中可行吗?

最佳答案

是的。您可以使用反射。像这样的:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

使用上面的代码,被调用的方法必须有访问修饰符public。如果调用非公共(public)方法,则需要使用 BindingFlags 参数,例如BindingFlags.NonPublic | BindingFlags.Instance:

Type thisType = this.GetType();
MethodInfo theMethod = thisType
.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);

关于c# - 从 C# 中的字符串调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/540066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com