调用该函数,该函数存储在字符串变量中

2023-12-03

它可能是重复的

如何在.NET中动态调用类的方法?

and of

如何实现动态调用函数,没错,调用的函数是由数据库值决定的,使用c#

但上述两个解决方案正如答案所说很复杂,我想不适合初学者。

and

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

like

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获取函数名的字符串值

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

problem

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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调用该函数,该函数存储在字符串变量中 的相关文章

随机推荐