do this without using an “if” | if(s == “value1”){…} else if(s == “value2”) { …}

前端 未结 18 2021
温柔的废话
温柔的废话 2021-01-30 09:36

According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also

18条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 09:54

    write classes with virtual methods which is derived from your abstract base class SomeThingWriter.

    then every class which are derived from base class should implement a function like writeSomething or whatever you want.

    abstract class MyBaseClass
    {
         public abstract void writeSomething();
    }
    
    class DerivedClass1 : MyBaseClass
    {
        public override void writeSomething()
        {
            Writeln("something else here  1");
        }
    }
    
    class DerivedClass2 : MyBaseClass
    {
        public override void writeSomething()
        {
            Writeln("something else here  2");
        }
    }
    

    than just call like

    MyBaseClass c = new DeriveClass1();
    c.writeSomething();
    c = new DerivedClass2();
    c.writeSomething();
    

提交回复
热议问题