简体   繁体   中英

Reuse parameters when calling base constructor c#

I have the following class structure:

class Foo{
  public Foo(Bar bar, Qux qux){
    ...
  }
}

class Bar{}

class Qux{
  public Qux(Bar bar){
    ...
  }
}

And I want create a new class FooFoo with a constructor without parameters something like:

class  FooFoo:Foo{
     public FooFoo():base(var bar=new Bar(), new Qux(bar)) {
          //this do not compile
     }
}

How can I do it?

Currently my solution is:

class  FooFoo:Foo{

     public static FooFoo instantiate(){
        var bar= new Bar();
        var qux= new Qux(bar);
        return new FooFoo(bar,qux);
     }

     private FooFoo(Bar bar, Qux qux):base(bar,qux) {
     }
}

But it sound bad, right?

How about:

public class FooFoo : Foo
{
    public FooFoo() : this(new Bar()) 
    {
    }

    public FooFoo(Bar bar) : base(bar, new Qux(bar)) 
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM