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

后端 未结 7 778
遥遥无期
遥遥无期 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:52

    Having virtual property which would be overriden in derived classes should do the trick:

    class Role
    {
        public virtual string Destination { get { return "Home"; } }
    }
    class Manager : Role
    {
        public override string Destination { get { return "ManagerHome;"; } }
    }
    class Accountant : Role
    {
        public override string Destination { get { return "AccountantHome;"; } }
    }
    class Attender : Role
    {
        public override string Destination { get { return "AttenderHome;"; } }
    }
    class Cleaner : Role
    {
        public override string Destination { get { return "CleanerHome;"; } }
    }
    class Security : Role { }
    

    I didn't make the property abstract, to provide default Home value when it's not overriden in derived class.

    Usage:

    string destination = (new Accountant()).Destination;
    Console.WriteLine(destination);
    Console.ReadLine();
    

提交回复
热议问题