C#设置值之前的数据验证

时间:2014-09-22 00:58:45

标签: c# validation constructor

所以,我的挑战是:

构造函数应该调用基类构造函数来初始化帐户的名称,编号和余额。它还应该在自己的类setInterestRate中调用一个方法,该方法应该设置InterestRate变量并验证该速率是一个正数。如果传入的利率为负,则将利率设置为零。

这对我来说似乎相当简单,但是VS正在为我的setInteresteRate方法执行ping操作(并非所有代码路径都返回一个值)。我一定错过了什么,但我不确定是什么。有什么建议?这是我的代码:

public SavingsAccount(string AccountName, int AccountNumber, decimal Balance, double rate) : base(AccountName, AccountNumber, Balance)
    {
        InterestRate = rate;
    }

    public double setInterestRate(double rate)
    {
        if (rate >= 0)
        {
            InterestRate = rate;
        }
        else
        {
            InterestRate = 0;
        }
    }

1 个答案:

答案 0 :(得分:1)

使你的setInterestRate方法无效,如下所示。因为你只需要设置InterestRate。

 public void setInterestRate(double rate)

如果您的方法中有返回类型,则必须返回一个值。多数民众赞成你的错误显示。

<强>建议

将您的InterestRate设为如下样本的属性并在那里进行验证

double interestRate;
    public double InterestRate
    {
        get
        {
            return interestRate;
        }
        set
        {
            if (value >= 0)
            {
                interestRate = value;
            }
            else
            {
                interestRate = 0;
            }
        }
    }