.Net 4.0 Optimized code for refactoring existing “if” conditions and “is” operator

后端 未结 7 821
遥遥无期
遥遥无期 2021-01-06 18:02

I have following C# code. It works fine; but the GetDestination() method is cluttered with multiple if conditions by using is operator.

In

7条回答
  •  萌比男神i
    2021-01-06 18:34

    One way to do it would be to use a map instead of an if:

    //(psuedocode)
    private Dictionary RoleMap;
    
    void SomeInitializationCodeThatRunsOnce()
    {
      RoleMap.Add(typeof(Manager), @"\ManagerHome");
      RollMap.Add(typeof(Accountant), @"\AccountantHome");
      // ect...
    }
    
    string GetDestination(Role x)
    {
      string destination;
      if(!RoleMap.TryGet(x.GetType(), out destination))
        destination = @"\Home";
      return destination;
    }
    

    Further reading: http://www.hanselman.com/blog/BackToBasicsMovingBeyondForIfAndSwitch.aspx

提交回复
热议问题