看板 C_Sharp 關於我們 聯絡資訊
第一次po文請見諒 我大概知道c# call by value / reference是怎麼回事 但使用上還是覺得怪怪的 在c++中,當我們把傳入函式的參數設成傳址或傳參考, 意味著該值會在函式中被更改 另一方面,如果只是傳值使用者不必擔心傳入的變數會被改掉 但c#中,class object本身就是reference type 不論是傳參考或傳值都有可能被修改 如果我是class 的使用者, 難道不該(需)知道該物件有沒有被修改過嗎? 感覺抖抖的 或者說,我該用什麼角度去理解c#對class object的操作呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.77.32.131 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1505826669.A.363.html
testPtt: 就要自己new物件去複製防止修改阿 09/19 22:00
undyingworld: 原來要手動複製呀。也就是說傳進去的class物件基本 09/19 23:42
undyingworld: 上就變成未知數了 09/19 23:42
lightyen: 不需要知道 09/20 00:18
lightyen: 因為有public private 09/20 00:19
ssccg: 跟C++比的話,就當C#裡reference type的都是pointer就好 09/20 00:30
ssccg: 想有像C++那種on stack object可以用value type(struct) 09/20 00:31
undyingworld: 或許我更在意可讀性的問題,一個函式接收class obj 09/20 12:13
undyingworld: ect當參數,我怎麼知道這是output 還是input,因為 09/20 12:13
undyingworld: 不需要out / ref 關鍵字就可以修改其值 09/20 12:13
undyingworld: 使用struct 的方式無法解決某些情況,例如使用別人 09/20 12:19
undyingworld: 寫的code,無法自己決定用class或struct,但又必須 09/20 12:19
undyingworld: 用到該class object 當參數 09/20 12:19
ssccg: C#世界(或是說用這種傳參數方法的語言都是)不太會去分input 09/20 13:13
ssccg: output參數,你可能得習慣,實際行為看API說明就好 09/20 13:15
Litfal: 不懂你的問題,class當參數就是要被使用,一個人傳過去變 09/20 16:12
Litfal: 另一個人不奇怪嗎?真要只傳資料請另外開DTO class 09/20 16:12
Litfal: 知道物件有沒有被修改過?什麼都想知道不就和OO的封裝原則 09/20 16:21
Litfal: 矛盾了? 09/20 16:21
shadow0326: 我想原po的問題大概是C#沒有const參數吧? 這只能靠設 09/20 18:42
shadow0326: 計模式迴避掉 09/20 18:42
undyingworld: 感謝各位回應,也許是從c++的角度來看c#才覺得怪怪 09/20 18:51
undyingworld: 的,對我來說已經很習慣透過c++的參數型態來判斷是 09/20 18:51
undyingworld: 否期待該參數會被函式改變,但c#在決定使用class或 09/20 18:51
undyingworld: struct的時候就決定好之後只能當作ref或value 使用 09/20 18:51
undyingworld: 即使在c++當中沒有使用const ,我仍然可以預想傳值 09/20 18:54
undyingworld: 時原本的物件不會被改變。 09/20 18:54
undyingworld: 而會被改變的參數我則認為他是函數的outputs 之一 09/20 18:56
undyingworld: 如果傳入的所有參數都可能被改變,那我只能透過註 09/20 18:58
undyingworld: 解或說明檔才能知道哪個是input 哪個是output 09/20 18:58
undyingworld: 對我來說這樣會降低程式碼的可讀性和可維護性 09/20 19:00
ssccg: 在這邊的世界裡,反倒是覺得把參數當output是詭異的想法... 09/20 19:09
ssccg: 一個物件自己能控制自己能被做哪些操作,不是由caller也不 09/20 19:11
ssccg: 是由callee function來決定,是比較純物件導向的看法吧 09/20 19:12
ssccg: 真的常有不想被改的需求的class,通常是準備個immutable版 09/20 19:12
ssccg: 的,setter不給用就好了 09/20 19:13