avoiding if statements

前端 未结 24 755
心在旅途
心在旅途 2021-01-30 08:39

I was thinking about object oriented design today, and I was wondering if you should avoid if statements. My thought is that in any case where you require an if statement you ca

24条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 09:43

    Avoiding If Statement: There are many ways to do, one of them is below:

    int i=0;
    if(i==1)
    {
    //Statement1
    }
    
    if(i==2)
    {
    //Statement2
    }
    
    if(i==3)
    {
    //Statement3
    }
    
    if(i==4)
    {
    //Statement4
    }
    

    Using Dictionary and delegate:

    delegate void GetStatement ();
    
    Dictionary valuesDic=new Dictionary();
    
    void GetStatement1()
    {
    //Statement1
    }
    void GetStatement2()
    {
    //Statement2
    }
    void GetStatement3()
    {
    //Statement3
    }
    
    
    void GetStatement4()
    {
    //Statement4
    }
    
    void LoadValues()
    {
    valuesDic.Add(1,GetStatement1);
    valuesDic.Add(2,GetStatement2);
    valuesDic.Add(3,GetStatement3);
    valuesDic.Add(4,GetStatement4);
    
    }
    

    Replacing If Statement:

    int i=0;
    valuesDic[i].Invoke();
    

提交回复
热议问题