作者evirtues (don't care)
看板C_Sharp
標題Re: [問題] 書中的問題
時間Sun Dec 26 22:01:52 2010
※ 引述《amonsat (amonsat)》之銘言:
: 這是一本叫深入淺出C#的書(97出版),在第201頁有個改錯的習題,
: 那本書有解答也就是我標的#1,#2,#3,#4
: ,以下是程式碼(註解的部分是我的改錯):
: class GumballMachine
: {
: private int gumballs;
: private int price;
: public int Price
: {
: get
: {
: return price;
: }
: }
price是private field而取值方式是用public field(Price)來取,
依照定義price就叫做支援欄位(backing field)。
建議看英文版的MSDN比較清楚
: public GumballMachine(int gumballs, int price)
: {
: gumballs = this.gumball; //應該改成this.gumball=gumball;#1
: price = Price; //應該改成Price=price;#2
: }
: public string DispenseOneGumball(int price, int coinsInserted)//我覺得沒錯啊#3
引數用price是OK的,只是會遮蔽掉先前所宣告的price,
在這個function下所使用的price就是指這個引數,
也就是你在外部呼叫時所餵進去的值,其實書應該建議你去掉這個引數。
: {
: //下面應該改成if(coinsInserted >= price)
: if (this.coinsInserted >= price)//check the field(這個是書上寫的)#4
書上應該是要你使用外面宣告的price而非引數的price,
所以應該要用this.price取得外面那個price的值。
所在的類別內沒有coinsInserted欄位所以this.coinsInserted會有問題。
: {
: gumballs -= 1;
: return "Here's your gumball";
: }
: else
: {
: return "Please insert more coins";
: }
: }
: }
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.231.107.141
推 amonsat:我想問的是這裡所稱"遮蔽"先前所宣告的price 12/26 23:10
→ amonsat:是說會把先前設定好price的值給覆蓋嗎? 12/26 23:10
→ andymai:不是覆蓋~而是你不加this~會誤取~所以這樣寫是自找麻煩 12/26 23:12