简体   繁体   中英

Override base protected property in c#

Slight newbie question.

I have a base class for payments. All share the same properties apart from additional extras. One of the properties is a postUrl . In the base this is empty but in the child classes each one has its own url. This should not be allowed to be accessed from outside the classes and it fixed and should not change. How do I go about overriding the property in a child class?

eg

class paymentBase
{
    public int transactionId {get;set;}
    public string item {get;set;}
    protected virtual postUrl = String.empty; // can't be accessed from outside inheritance / public / protected?

    public void payme();
}

class paymentGateWayNamePayment : paymentBase
{
    protected override postUrl { 
        get { return "http://myurl.com/payme"; }
    }
}

How would I go about doing this?

Thanks in advance

You should be able to accomplish it if you make your postUrl an actual virtual property, like this:

class paymentBase
{
    public int transactionId {get;set;}
    public string item {get;set;}
    protected virtual postUrl { get { return String.Empty; }}

    public void payme();
}

class paymentGateWayNamePayment : paymentBase
{
    protected override postUrl {get { return "http://myurl.com/payme"; } }
}

Based on your requirements, I would recommend using an interface because posturl is a generic property that can be used on anything eg a page post back, a control post back, your class might use it etc. This interface can be used as needed by any class.

interface IPostUrl
{
    string postUrl { get; }
}

class paymentBase
{
    public int transactionId {get;set;}
    public string item {get;set;}
    public void payme(){}
}

class paymentGateWayNamePayment : paymentBase, IPostUrl
{
    public string postUrl
    {
        get { return "http://myurl.com/payme"; }
    }
}

I know this is a late entry but if you want the postUrl value to be set once by the sub class and then never again you need to make it a private value to the base class.

abstract class paymentBase
{
    public paymentBase(string postUrl) { this.postUrl = postUrl; }
    public int transactionId { get; set; }
    public string item { get; set; }
    protected string postUrl { get; private set; }

    public void payme();
}

class paymentGateWayNamePayment : paymentBase
{
    public paymentGateWayNamePayment() : base("http://myurl.com/payme") {  }
}

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