Can I use the default method in the base class, which is always called before child implementations?

C # here - is it possible for an abstract base class to define a method with default behavior and call this default value before implementing a child class? For instance:

public abstract class Base
{
    public virtual int GetX(int arg)
    {
        if (arg < 0) return 0;
        // do something here like "child.GetX(arg)"
    }
}

public class MyClass : Base
{
    public override int GetX(int arg)
    {
        return arg * 2;
    }
}

MyClass x = new MyClass();
Console.WriteLine(x.GetX(5));    // prints 10
Console.WriteLine(x.GetX(-3));   // prints 0

Basically, I don’t want the same template in every child implementation ...

+3
source share
6 answers

Defendant, who will be the issue. The way I came across this problem in the past is to create 2 methods that are publicly available in the base class and protected by an abstract (possibly virtual, without implementation).

public abstract class Base
{
  public int GetX(int arg)
  {
    // do boilerplate

    // call protected implementation
    var retVal = GetXImpl(arg);

    // perhaps to more boilerplate
  }

  protected abstract int GetXImpl(int arg);
}

public class MyClass : Base
{
  protected override int GetXImpl(int arg)
  {
    // do stuff
  }
}
+6
source

, , , ,

+2

, , ,

0

, base.GetX(...).

, . , - :

public abstract class Base
{
    public override int GetX(int arg)
    {
        if(arg < 0) return 0;

        return OnGetX(arg);
    }

    protected abstract OnGetX(int arg);
}

public class MyClass : Base
{
    protected override int OnGetX(int arg)
    {
        return arg * 2;
    }
}

MyClass x = new MyClass();
Console.WriteLine(x.GetX(5));    // prints 10
Console.WriteLine(x.GetX(-3));   // prints 0
0

- . , , . , ,

public void ExecuteSteps()
{
  Step1(); //Defined in base, can't be overridden.
  Step2(); //Defined as virtual in base, so sub-classes can override it
} 

, : http://tech.puredanger.com/2007/07/03/pattern-hate-template/

0

, , " " , ; , , , .

There is a way to provide this, but it's a little ugly. If the target X.ChainedMethod()should only be called from within X.WrapperMethod(), create a dummy open class Y inside X that has a constructor internal, and a private dummy class Zthat inherits from Yand has an open parallelless constructor. Then announce X.ChainedMethod<T>() where T:Z, new(). The only possible class that would fill these restrictions would be Y, and nothing outside Xcould access Y.

0
source

All Articles