C# - 仅在子类中调用重写方法

时间:2017-05-04 21:07:28

标签: c# oop

我正在尝试解决以下OO问题。我知道它有点味道,但我必须适应现有的设计。请考虑以下代码段:

class Parent
{
   public virtual Context GetContext()
   {
       return new Context(true);
   }

   public virtual GetData()
   {
       var context = GetContext();
       var result = Query(context);
       return result;
   }

   public string GetData2()
   {
       var context = GetContext();
       var result = Query(context);
       return result;
   }

}

class Child : Parent
{
   public override Context GetContext()
   {
       return new Context(false);
   }

   public override GetData()
   {
       var context = GetContext();
       var result = Query(context);
   }
}

我想要以下结果:

new Parent().GetData() => would call Parent.GetContext();
new Parent().GetData2() => would call Parent.GetContext();
new Child().GetData() => would call Child.GetContext();
new Child().GetData2() (not overriden in Child) => would call Parent.GetContext();

实际结果是:

new Parent().GetData() => calls Parent.GetContext();
new Parent().GetData2() => calls Parent.GetContext();
new Child().GetData() => calls Child.GetContext();
new Child().GetData2() => calls Child.GetContext();

2 个答案:

答案 0 :(得分:-1)

你需要覆盖(在这种情况下替换)GetData2函数:

v

请记住,使用new修饰符不会覆盖基本函数,如果替换它,这意味着如果您将 class Child : Parent { public override Context GetContext() { return new Context(false); } public override GetData() { var context = GetContext(); var result = Query(context); } public new string GetData2() { var context = base.GetContext(); return Query(context); } } 转换为Child并调用Parent它将调用旧功能,而不是新的功能。

答案 1 :(得分:-2)

你可以有类似的东西:

class Parent
{
   public virtual Context GetContext()
   {
       return GetContextParentCall();
   }

   private Context GetContextParentCall()
   {
       return new Context(true);
   }

   public virtual GetData()
   {
       var context = GetContext();
       var result = Query(context);
       return result;
   }

   public string GetData2()
   {
       var context = GetContextParentCall();
       var result = Query(context);
       return result;
   }

}