C#继承 - 为派生类添加受保护的成员

时间:2017-04-08 11:46:02

标签: c# inheritance

大家好我在C#程序中遇到一些问题。我在基类中有以下代码(它有2个直接引用_Balance的派生类)。

public class FloatIncreasing
{
    private float _Value;
    public float Value {
        get {
            return _Value;
        }
        set {
            ValueChangeEvent(this, _Value >= value);
            _Value = value;
        }
    }
    public Boolean HasIncreased { get; private set; }
    public event EventHandler<Boolean> ValueChangeEvent;
    public FloatIncreasing() {
        this.ValueChangeEvent += OnValueChanged; 
    }
    public virtual void OnValueChanged(Object sender, Boolean value) {
        HasIncreased = value;
        // You can add a more appropriate default behavior in here. 
    }
}

现在我知道因为_Balance是私有的,我的程序没有编译,因为它的保护级别无法访问。我也知道我需要在这个类中添加一个或多个受保护的成员,以允许派生成员修改_Balance。我只是不知道什么是最好的方法。显然,派生类中对_Balance的直接引用也需要改变。

非常感谢任何建议,谢谢!

2 个答案:

答案 0 :(得分:0)

protected制定者添加到Balance

using System;
namespace BankAccounts  
{  
   class Account  
   {  
       protected Account(decimal balance)  
       { _Balance = balance; }  

       protected decimal _Balance;
       public decimal Balance
       {
           get { return _Balance; }
           protected set { _Balance = value; }
       }

       public override string ToString()
       {
           return string.Format("Balance: {0:c}", _Balance);
       }
   }

答案 1 :(得分:0)

根据您在另一个answer的评论中要求的内容,您可以手动实现封装(不使用自动属性),如下面的代码所述:

public class Account{

   private Decimal Balance; // Since you mentioned this private field is a MUST
   public Decimal GetBalance() {
       return Balance;
   }
   // Or public depending on your needs
   protected void SetBalance(Decimal Balance) {
       this.Balance = Balance; 
   }
}