使用属性中的set validation在构造函数中设置私有字段

时间:2011-11-14 00:27:18

标签: c# constructor properties

那么..如何使用构造函数内的属性验证私有实例变量(字段)?

我有这个代码可行,但我强烈认为这不是应该如何完成的:

class Account
    {
        private decimal acctBalance = 0;

        public decimal AcctBalance
        {
            get
            {
                return acctBalance;
            }
            set
            {
                if (acctBalance >= 0)
                    acctBalance = value;
                else
                {
                    Console.WriteLine("Invalid balance, balance set to 0");
                    acctBalance = 0;
                }
            }
        }

        public Account(decimal balance)
        {
            acctBalance = balance;
            AcctBalance = acctBalance;
        }
    }

我只是想确保这是正确的方法

谢谢!

1 个答案:

答案 0 :(得分:3)

尽管存在一些问题,但您的方法大多是正确的。我修复了它们,然后用我做过的评论注释了代码。

class Account
{
    private decimal acctBalance = 0;

    public decimal AcctBalance
    {
        get
        {
            return acctBalance;
        }
        set
        {
            //modified to check value instead of acctBalance
            if (value >= 0)
                acctBalance = value;
            else
            {
                Console.WriteLine("Invalid balance, balance set to 0");
                acctBalance = 0;
            }
        }
    }

    public Account(decimal balance)
    {
        //redundant! Changing AcctBalance changes acctBalance
        //acctBalance = balance;
        AcctBalance = balance; 
    }
}