【问题标题】:calling the function, which is stored in a string variable调用函数,该函数存储在字符串变量中
【发布时间】:2011-04-27 21:37:49
【问题描述】:

它可能与

重复

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

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

问题

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

..

【问题讨论】:

    标签: c# function web dynamic


    【解决方案1】:

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

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

    【讨论】:

    【解决方案2】:

    我看到了 2 个解决方案:

    1. 您需要将函数 ID 映射到 真正的函数名
    2. 呼叫 type.GetMethods() 获取所有列表 方法并选择正确的方法

    【讨论】:

    猜你喜欢
    • 2012-05-17
    • 2011-01-07
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多