c# - 调用存储在字符串变量中的函数

标签 c# function web dynamic

它可能是重复的

How to dynamically call a class' method in .NET?

和的

how to achieve calling a function dynamically, thats right the function to be called is decided from database values, using c#

但是上面两个有解决方案,正如答案所说的那样复杂,我猜不适合初学者。

两种解决方案都包含“类型”,我认为从代码中可以看出该类型用于定义方法所属的类。

喜欢

static void caller(String myclass, String mymethod)
    {
        // Get a type from the string 
        Type type = Type.GetType(myclass);
        // Create an instance of that type
        Object obj = Activator.CreateInstance(type);
        // Retrieve the method you are looking for
        MethodInfo methodInfo = type.GetMethod(mymethod);
        // Invoke the method on the instance we created above
        methodInfo.Invoke(obj, null);
    }

但我最初的网站只包含一个所有功能通用的类,

具有“函数名称”“函数ID”的数据库

假设:- 函数名与代码中的完全相同

我只想实现以下目标

  • 根据文本框中提到的id得到函数名的字符串值

  • 现在调用该函数,其名称在字符串变量中

问题

方法信息,需要“type.GetMethod(mymethod);”

..

最佳答案

为了调用函数,您需要指定声明此函数的类型。如果您要调用的所有函数都在一个公共(public)类上声明,您可以执行以下操作:

static void CallFunc(string mymethod)
{
    // Get a type from the string 
    Type type = typeof(TypeThatContainsCommonFunctions);

    // Create an instance of that type
    object obj = Activator.CreateInstance(type);

    // Retrieve the method you are looking for
    MethodInfo methodInfo = type.GetMethod(mymethod);

    // Invoke the method on the instance we created above
    methodInfo.Invoke(obj, null);
}

如果您要调用的函数是静态的,则不需要该类型的实例:

static void CallFunc(string mymethod)
{
    // Get a type from the string 
    Type type = typeof(TypeThatContainsCommonFunctions);

    // Retrieve the method you are looking for
    MethodInfo methodInfo = type.GetMethod(mymethod);

    // Invoke the method on the type
    methodInfo.Invoke(null, null);
}

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

相关文章:

c# - 访问 propertyinfo 中的属性

javascript - 从函数属性访问对象属性在 Firefox 中不起作用

c - 如何修改已传递给 C 函数的指针?

linux - 是否可以将选项(不是参数)传递给 bash 中的函数?

web - 如何估算网站带宽

c# - 在 WCF RESTful 服务中访问请求主体

c# - 当我重新运行应用程序时,图片框不显示最后上传的图像

c# - 枚举相等(和 EventHandlerList 的键)

javascript - 在 jquery javascript 中选择第 n 个子级

javascript - 是否可以在不使用 WebRTC 的情况下通过网络上的 websocket 进行视频通话?