Re: [問題] 如何在C#實現JS的 callBack ?--解決回覆

看板C_Sharp作者 (石理克)時間7年前 (2017/06/16 14:33), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串1/1
※ 引述《sakyer (石理克)》之銘言: : 問題網頁版: : https://goo.gl/uPmWK4 : 問題圖片版: : https://goo.gl/lmLtoh : 為了從別人的程式碼學習 c# ,我正試著將一個JS程式重寫成C#。 : 其中這段 eachCell 方法不知道在 C# 中該如何實現... : 煩請各位大大給予建議與指教,謝謝! : // Get available cells in Grid ========================= : Grid.prototype.availableCells = function () { : var cells = []; : this.eachCell(function (x, y, tile) { : if (!tile) { : cells.push({ x: x, y: y }); : } : }); : return cells; : }; : // Call callback for every cell========================= : Grid.prototype.eachCell = function (callback) { : for (var x = 0; x < this.size; x++) { : for (var y = 0; y < this.size; y++) { : callback(x, y, this.cells[x][y]); : } : } : }; 網頁版看比較清楚: https://goo.gl/uPmWK4 經版上大大提點後,去研究一下委派的使用 最後使用委派:Action完成了我想要的功能 P.S 會再試試看改用 Func 會有什麼不同,目前還不理解他與Action的差異 ================================ List<Tile> getAvailableCell() { List<Tile> cells = new List<Tile>(); Action<int, int, Tile> finder = (x, y, t) => { if (t == null) cells.Add(new Tile(x, y, -1)); }; eachCell(finder); return cells; } void eachCell(Action<int, int, Tile> act) { for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { act(x, y, cells.ContainsKey(new Vector2(x, y)) ? cells[new Vector2(x, y)] : null); } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.251.182.68 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1497594811.A.684.html

06/16 15:10, , 1F
Action沒有回傳值 Func有回傳值
06/16 15:10, 1F
文章代碼(AID): #1PGtkxQ4 (C_Sharp)