C#属性 - 在setter访问器中添加逻辑

Dav*_*e B 1 c# if-statement properties set

我正在尝试设置该属性的值,因此如果该帐户进入借方,则需要收取10的费用.我尝试过多种方式对属性CurrentBalance进行编码,包括借记(10),值-10和账户余额-10,但这些方法都不起作用.代码编译但不收取费用.我究竟做错了什么?

    public void Credit(decimal amount)
    {
        accountBalance += amount; //add to balance
    }

    public void Debit(decimal amount)
    {
        accountBalance -= amount; //subtract amount
    }

    public decimal CurrentBalance
    {
        get
        {
            return accountBalance;
        }
        set
        {
            if (value < 0) // if less than zero debit account by 10
            {
              value = accountBalance -10; // charge account
            }
            accountBalance = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

tal*_*eth 5

这将是一个更好的方式来实现你想要的:

public void Credit(decimal amount)
{
    accountBalance += amount; //add to balance
}

public void Debit(decimal amount)
{
    accountBalance -= amount; //subtract amount
    if(accountBalance < 0)
    {
        accountBalance -= 10;
    }
}

//make this a readonly property and use the debit and credit functions to adjust it
public decimal CurrentBalance
{
    get
    {
        return accountBalance;
    }
}
Run Code Online (Sandbox Code Playgroud)