Skip to main content
 首页 » 编程设计

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

2024年02月24日30Leo_wl

它可能是重复的

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