首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中从字符串调用函数

在C#中从字符串调用函数
EN

Stack Overflow用户
提问于 2009-02-12 12:49:30
回答 6查看 219.1K关注 0票数 154

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

代码语言:javascript
复制
$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

这在.Net中是可能的吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-02-12 04:53:33

是。您可以使用反射。如下所示:

代码语言:javascript
复制
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

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

代码语言:javascript
复制
Type thisType = this.GetType();
MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);
票数 292
EN

Stack Overflow用户

发布于 2009-02-12 04:57:56

您可以使用反射调用类实例的方法,执行动态方法调用:

假设您在实际实例(This)中有一个名为hello的方法:

代码语言:javascript
复制
string methodName = "hello";

//Get the method information using the method info class
 MethodInfo mi = this.GetType().GetMethod(methodName);

//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);
票数 80
EN

Stack Overflow用户

发布于 2009-02-12 04:57:40

代码语言:javascript
复制
class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(MyReflectionClass);
            MethodInfo method = type.GetMethod("MyMethod");
            MyReflectionClass c = new MyReflectionClass();
            string result = (string)method.Invoke(c, null);
            Console.WriteLine(result);

        }
    }

    public class MyReflectionClass
    {
        public string MyMethod()
        {
            return DateTime.Now.ToString();
        }
    }
票数 40
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/540066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档