2014-09-25 14 views
0

我正在做功課,並與一個屬性,我需要作出不接受負面價值堅持。如何限制屬性設置器不接收低於零的值?

我有這個代碼的財產。如何讓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); 


    } 
+1

imho最好的做法是在屬性訪問器中只執行簡單的任務,諸如檢查空值之類的非平凡任務更適合於在將其分配給屬性之前檢查null的方法。 – 2014-09-25 11:43:27

+0

我用一種方法做了,但老師說這不是正確的方法。而且在整個網絡中,用戶都表示最好使用一種方法。 – 2014-09-25 11:49:56

+0

講師講授理論,該領域的專業人員教實用性/可讀性/可維護性/常識...考慮http://msdn.microsoft.com/en-gb/library/w86s7x04.aspx有一個if語句,但如果這個月被設置爲13 ...沒有......好吧,那就是褲子......如果它是13(或者你的情況爲null),那麼你總是想做點什麼,並且屬性的特殊方法訪問器不是最好的地方它。 – 2014-09-25 13:30:14

回答

6

你或許應該拋出一個ArgumentOutOfRangeException:

public decimal Balance 
{ 
    get { return balance; } 
    private set 
    { 
     if (value < 0) 
      throw new ArgumentOutOfRangeException("Only positive values are allowed"); 

     balance = value; 
    } 
} 

但默認爲0,或者什麼都不做,也可以是一個選項,具體取決於具體要求。

1
public decimal Balance 
{ 
    get {return balance;} 
    private set 
    { 
     if (value >= 0) 
     { 
      balance = value; 
     } 
    } 

只要做什麼,如果值小於0,或拋出一個ArgumentException

0

你可以只從模子返回(你不需要處理它),或者如果你要處理它,拋出異常。

+1

只是在更深層次上思考這個問題......如果你正在談論一個賬戶的平衡,從一個真實的詞對象的角度來看,外部事物不會​​設置'平衡'。他們添加和刪除確定餘額的金額。因此,在這種情況下,更好的設計將只有吸氣劑,並具有會影響私密餘額數量的加減法方法。 – Ian 2014-09-25 11:41:48