在控制台应用程序中使用某些条件覆盖方法

Method Override with some condition in Console application

我正在创建一个控制台应用程序。我有一个 class,其中我写了一些方法。现在我想在另一个 class 中重写那个 class 的一些方法。但是只有当条件满足时才应该覆盖它。

例如,

public partial Class MainClass
{
   public string GetPath()
   {
      string temp =  Method1();
      return temp;
   }

    protected virtual string Method1()
    {
       //logic
    }


}

如果满足某些条件,则只应调用覆盖的方法

public partial class ChildClass : MainCLass
{
    public override void Method1()
    {
        //MY Logic
    }
}

我怎样才能做到这一点?可以这样做吗?

ChildClass 中你可以这样做:

public partial class ChildClass : MainCLass
{
    public override void Method1()
    {
        if(condition)
        {
            base.Method1();

            return;
        }

        //YOUR LOGIC
    }
}

示例

public class A
    {
        public virtual void MethodA()
        {
            Console.WriteLine("A:MethodA");
        }
    }

    public class B : A
    {
        public bool CallBase { get; set; }

        public B()
        {
            CallBase = false;
        }

        public override void MethodA()
        {
            if (CallBase)
            {
                base.MethodA();

                return;;
            }

            Console.WriteLine("B:MethodA");
        }
    }

    class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();

        a.MethodA();
        b.MethodA();

        b.CallBase = true;

        b.MethodA();

        A c = new B();

        c.MethodA();

        A d = new B(true);

        d.MethodA();

        Console.ReadKey();
    }
}

输出

A:MethodA B:MethodA A:MethodA B:MethodA A:MethodA