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

后端 未结 7 777
遥遥无期
遥遥无期 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条回答
  •  悲&欢浪女
    2021-01-06 18:56

    This is a strongly typed, imperative language so if statements and type checking are going to happen.

    Having said that, have you considered a virtual method on Role that can be overridden to provide a destination string?

    A further alternative, a lookup table!

    Dictionary paths = new Dictionary()
    {
        { typeof(Manager),  @"\ManagerHomeA" }
        { typeof(Accountant),  @"\AccountantHomeC" }
        { typeof(Cleaner),  "Cleaner" }
    }
    
    string path = @"\Home";
    if(paths.ContainsKey(x.GetType())
        path = paths[x];
    

提交回复
热议问题