代码之家  ›  专栏  ›  技术社区  ›  Michael Grinnell

是否可以使用基类中的if条件来影响子类

  •  0
  • Michael Grinnell  · 技术社区  · 7 年前

    我试图弄清楚是否可以在基类中使用if语句,这取决于父类方法的继续执行或只是返回值。

    这是我举的一个小例子。

    创建两个父类的主类

    public class Program
    {
        public static void Main()
        {
            Class1 c1 = new Class1();
    
            Class2 c2 = new Class2();
    
            c1.test();
    
            c2.test();
    
        }
    }
    

    这是包含要进行ovveriden的方法的基类

    public class baseClass
    {
    
        public bool b = true;
    
        public virtual void test()
        {
            if(!b)
            {
                Console.WriteLine("b is true returning");
                return;
            }
        }
    }
    

    父类1

    public class Class1 : baseClass
    {
        public override void test()
        {
            base.test();
    
            //the below line should only execute if b is true
            Console.WriteLine("Executing a method unique to Class1");
        }
    }
    

    父类2

    public class Class2 : baseClass
    {
        public override void test()
        {
            b = false;
            base.test();
    
            //the below line should only execute if b is true
            Console.WriteLine("Executing a method unique to Class2");
        }
    }
    

    我真的简化了它,它看起来有点毫无意义,但我试图解释我想用代码做什么。

    基本上,在我的基类中,我将检查列表是否为空,如果是,我只想返回,而不继续执行父类方法。但是,如果它不是空的,那么每个父类将对列表执行不同的操作。

    编辑 这是一把小提琴,我试图实现的是它不应该打印出class2.test()的行。

    https://dotnetfiddle.net/p67UgJ

    1 回复  |  直到 7 年前
        1
  •  3
  •   Philip Smith    7 年前

    您需要分离要重写的方法的部分,而不是重写整个方法。

    public class baseClass
    {
        public bool b = true;
    
        public void test()
        {
            if(!b)
            {
                BitThatNeedsToChange();
                return;
            }
        }
    
        protected virtual void BitThatNeedsToChange()
        {
            Console.WriteLine("b is true returning");
        }
    }
    

    在派生类中,您将重写 protected virtual 方法:

    public class Class1 : baseClass
    {
        protected override void BitThatNeedsToChange()
        {
            //the below line should only execute if b is true
            Console.WriteLine("Executing a method unique to Class1");
        }
    }