我正在做功課,並與一個屬性,我需要作出不接受負面價值堅持。如何限制屬性設置器不接收低於零的值?
我有這個代碼的財產。如何讓setter不讓用戶設置負值?
public decimal Balance
{
get {return balance;}
private set{ if (value >= 0)
{
balance = value;
}else if (value < 0)
{
??????
}
}
}
在這裏,這是我的主要()方法:
static void Main(string[] args)
{
BankAccountClass firstAccount = new BankAccountClass();
int userInputAccountNumber = int.Parse(Console.ReadLine());
firstAccount.addAccountNumber(userInputAccountNumber);
Console.WriteLine(firstAccount.AccountNumber);
}
imho最好的做法是在屬性訪問器中只執行簡單的任務,諸如檢查空值之類的非平凡任務更適合於在將其分配給屬性之前檢查null的方法。 – 2014-09-25 11:43:27
我用一種方法做了,但老師說這不是正確的方法。而且在整個網絡中,用戶都表示最好使用一種方法。 – 2014-09-25 11:49:56
講師講授理論,該領域的專業人員教實用性/可讀性/可維護性/常識...考慮http://msdn.microsoft.com/en-gb/library/w86s7x04.aspx有一個if語句,但如果這個月被設置爲13 ...沒有......好吧,那就是褲子......如果它是13(或者你的情況爲null),那麼你總是想做點什麼,並且屬性的特殊方法訪問器不是最好的地方它。 – 2014-09-25 13:30:14