[問題] this的使用..

看板C_Sharp作者 (Terry)時間12年前 (2012/05/18 00:45), 編輯推噓2(208)
留言10則, 4人參與, 最新討論串1/2 (看更多)
請教一下 最近突然想到this這個問題,試著寫一個小小的程式片段.. 發現,我好像沒搞懂... 我的理解是,因為欄位和參數有相同的名稱 參數會把欄位蓋掉 所以要用this,是說我要用這個欄位,而不要參數 然後我就寫了一小段 class thistest { public thistest (int testvalue) { this.testvalue = testvalue; MessageBox.Show("testvalue is "+ testvalue); } private int testvalue = 20; } //================== private void button1_Click(object sender, EventArgs e) { thistest value = new thistest(10); } 我的想法是說,按下按鈕,傳10進去 用this的話就是10 不用的話就是20 結果...好像加不加this都是10... 然後我另外還有想到一個是..為什麼參數和欄位名稱會是一樣的? 既然會蓋過去,不能設不一樣的就好了嗎? 麻煩前輩教導一下了 謝謝幫忙 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.42.112.154 ※ 編輯: bernachom 來自: 114.42.112.154 (05/18 00:47)

05/18 02:03, , 1F
欄位?參數? 是指寫在class的類別變數和method內的區域變數嗎?
05/18 02:03, 1F

05/18 02:04, , 2F
那不論如何運算,你的敘述都是show出區域變數的testvalue
05/18 02:04, 2F

05/18 02:12, , 3F
所以是說我的說法是對的,程式寫錯了嗎?
05/18 02:12, 3F

05/18 02:12, , 4F
因為我想要試著找出this和沒this的差別
05/18 02:12, 4F

05/18 02:13, , 5F
前輩能幫忙指正一下,該如何寫出看得出this差別的程式嗎
05/18 02:13, 5F

05/18 02:14, , 6F
謝謝您
05/18 02:14, 6F

05/18 08:28, , 7F
this就是代表class本身的instance
05/18 08:28, 7F

05/18 08:29, , 8F
理解成加不加this結果不一樣就不對了
05/18 08:29, 8F

05/18 13:45, , 9F
我理解錯了,謝謝您
05/18 13:45, 9F

05/21 10:00, , 10F
MessageBox.Show("testvalue is "+ this.testvalue);
05/21 10:00, 10F
文章代碼(AID): #1FjIirgW (C_Sharp)
文章代碼(AID): #1FjIirgW (C_Sharp)