Is there a way to manipulate the variables passed to the constructor of the child class before passing it to the base class?

Is there a way to defer a call to the superclass constructor so that you can manipulate the variables first?

Eg.

public class ParentClass
{
   private int someVar;

   public ParentClass(int someVar)
   {
       this.someVar = someVar;
   }
}

public class ChildClass : ParentClass
{
    public ChildClass(int someVar) : base(someVar)
    {
        someVar = someVar + 1
    }
}

I want to be able to send a new value for someVar(someVar + 1) to the constructor of the base class, and not the one that was passed to the constructor ChildClass. Is there any way to do this?

Thanks
Matt

+3
source share
2 answers
public class ChildClass : ParentClass
{
    public ChildClass(int someVar) : base(someVar + 1)
    {
    }
}

, , , base, .

+4

- ? ISomething .

public interface ISomething
{
    int DoSomething(int someVar);
}

public class Something : ISomething
{
    private int someVar;

    public Something(int someVar)
    {
        this.someVar = someVar;
    }

    public int DoSomething(int someVar)
    {
        return someVar + 1;
    }
}

public class ParentClass
{
   private int someVar;

   public ParentClass(ISomething something)
   {
       this.someVar = something.DoSomething(someVar);
   }
}

public class ChildClass : ParentClass
{
    public ChildClass(int someVar) : base(new Something(someVar))
    {

    }
}
0

Source: https://habr.com/ru/post/1741887/


All Articles