根据函数名称调用函数

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

代码
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/archive/2010/12/02/1894152.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值