calling the function, which is stored in a string variable

前端 未结 2 847
借酒劲吻你
借酒劲吻你 2021-01-24 05:15

it may be a duplicate of

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

and of

how to achieve calling a function dynamically, thats right the fun

相关标签:
2条回答
  • 2021-01-24 05:55

    In order to call a function you need to specify the type this function is declared on. If all functions you are going to call are declared on a common class you could do the following:

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

    If the functions you are going to call are static you don't need an instance of the type:

    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);
    }
    
    0 讨论(0)
  • 2021-01-24 06:15

    I see 2 solutions:

    1. you need to map function id to real function name
    2. call type.GetMethods() to get list of all methods and choose right one
    0 讨论(0)
提交回复
热议问题