根据函数名称调用函数

在写代码的时候我们经常会遇到以下的这种程序:

代码
namespace TestFunction
{
    
class Program
    {
        
public string CallFunction(string functionName)
        {
            
switch (functionName)
            {
                
case "abc":
                    {
                        
return aaa();
                    }
                
case "accountExist":
                    {
                        
return bbb();
                    }
                
default:
                    
return "";
            }
        }

        
private string aaa()
        {
            
return "aaa";
        }

        
private string bbb()
        {
            
return "bbb";
        }
    }
}

感谢上帝上面的列子里只有两个函数,但上天总是不会这么好的,我曾经遇到个上10个这样的调用;

正当我在努力的swtich、case 里,我就感觉很有问题。

于是开始研究一下能不能直接通过functionName直接就去调用那些函数呢?

上网查了一下果然是有的,所以把上面CallFunction的这个函数改良了一下:

代码
namespace TestFunction
{
    
class Program
    {
        
public string CallFunction(string functionName)
        {
            Assembly assebly 
= Assembly.GetExecutingAssembly(); 
            Type type 
= assebly.GetType("TestFunction.Program"); //通过命名空间和类名得到指定的类
            MethodInfo methodInfo = type.GetMethod(functionName);
            
object ob = Activator.CreateInstance(type);
            
object s = methodInfo.Invoke(ob, null);//null表示没有参数,如果有参数需要传入一个object数组
            return s.ToString(); 
        }

        
private string aaa()
        {
            
return "aaa";
        }

        
private string bbb()
        {
            
return "bbb";
        }
    }
}

更新于:2014/03/03,刚刚看到同事的一段代码,觉得有意思,存下来:

enum KKK
{
    Plus        = 0,
    Minus        = 1,
    Surplus        = 2,
    Except        = 3,
};
void PlusFun(int a,int b)
{
    printf("%d\n",a + b);
}
void MinusFun(int a,int b)
{
    printf("%d\n",a - b);
}
void SurplusFun(int a,int b)
{
    printf("%d\n",a * b);
}
void ExceptFun(int a,int b)
{
    printf("%d\n",a / b);
}
int _tmain(int argc, _TCHAR* argv[])
{
    int sw = 1;
    int a  = 2;
    int b  = 2;
    
    switch(sw)
    {
#define CALLFUNCTION(e,p) case (e):(p)(a,b); break
        CALLFUNCTION(Plus,PlusFun);
        CALLFUNCTION(Minus,MinusFun);
        CALLFUNCTION(Surplus,SurplusFun);
        CALLFUNCTION(Except,ExceptFun);
    }
    return 0;
}

这样的话再多的函数都不怕了! 

原文地址:https://www.cnblogs.com/Martin_Q/p/1894152.html