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

C# 调用存储在字符串变量中的函数,c#,function,web,dynamic,C#,Function,Web,Dynamic,它可能是 及 但是上面两个问题都有解决方案,正如答案所说的那样,这些解决方案很复杂,我想对初学者来说不是 及 这两种解决方案都包含“type”,我认为它来自定义该方法所属类的代码 像 但我最初的网站只包含一个所有函数都通用的类 具有“函数名”“函数id”的数据库 假定:-函数名与代码中的名称完全相同 我只想做到以下几点 根据文本框中提到的id获取函数名的字符串值 现在调用该函数,其名称在字符串变量中 问题 methodinfo需要“type.GetMethod(mymethod);” .

它可能是

但是上面两个问题都有解决方案,正如答案所说的那样,这些解决方案很复杂,我想对初学者来说不是

这两种解决方案都包含“type”,我认为它来自定义该方法所属类的代码

但我最初的网站只包含一个所有函数都通用的类

具有“函数名”“函数id”的数据库

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

我只想做到以下几点

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

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

问题 methodinfo需要“type.GetMethod(mymethod);”


..

要调用函数,需要指定该函数声明的类型。如果要调用的所有函数都在公共类上声明,则可以执行以下操作:

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

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

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);
}
我看到两种解决方案:

  • 您需要将函数id映射到 实函数名
  • 召唤 键入.GetMethods()以获取所有 方法和选择正确的方法
  • 我看到两种解决方案:

  • 您需要将函数id映射到 实函数名
  • 召唤 键入.GetMethods()以获取所有 方法和选择正确的方法

  • 可能需要一些空检查!;)你说函数是静态的是什么意思?一个函数怎么可能是动态的?请解释这一点,非常感谢静态和实例方法-请帮助可能的一些空检查!;)你说函数是静态的是什么意思?一个函数怎么可能是动态的?请解释这一点,将非常感谢静态和实例方法-请帮助