简体   繁体   中英

Use derived class property in base class constructor

In following code, I need Base class constructor to use Derived class property ServiceUrl . I cannot define ServiceUrl as static as it's value is computed based on Derived class constructor argument. I cannot pass ServiceUrl as constructor argument to Base class since the computation is not as trivial as illustrated and it may require access other fields in Base / Derived classes.

Any suggestions for the best way out? I have permissions to make any change to Base and Derived class structures to attain the purpose.

abstract class Base 
{
    public abstract string ServiceUrl { get; }

    public Base()
    {
        Console.WriteLine(ServiceUrl);
    }
}

class Derived : Base
{
    public override string ServiceUrl { get; private set; }

    public Derived(string rootUrl) : base()
    {
        ServiceUrl = rootUrl + "/service";
    }
}

The base class constructor will always be called before the derived class constructor. Therefore, there are exactly two solutions:

  1. Use a parameter in the constructor of your base class:

     abstract class Base { public string ServiceUrl { get; } public Base(string serviceUrl) { ServiceUrl = serviceUrl; Console.WriteLine(ServiceUrl); } } class Derived : Base { public Derived(string rootUrl) : base(rootUrl + "/service") { } } 
  2. Don't use the variable in the constructor. Use it at a later point.

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