Re: [姆咪] C# Generic 大師請盡

看板Marginalman作者 (動物園 公告)時間2年前 (2023/09/17 13:14), 2年前編輯推噓5(617)
留言14則, 10人參與, 2年前最新討論串2/2 (看更多)
※ 引述《nh60211as (xXx_5354M3_31M0_xXx)》之銘言: : 我想寫個 Generic Function 來讓輸入的 Function func 拋錯的時候回傳 null : static T? ExecuteGetNullable<T>(Func<T> func) where T : class? { : try { : return func.Invoke(); : } catch { : return null; : } : } : 這個用在 string type 編譯沒問題 : static string? GetNullableString() { : return ExecuteGetNullable(() => { : return ""; : }); : } : 可是用在 ulong type 的時候編譯器就不高興了 : https://i.imgur.com/ZH7SmC9.png
: static ulong? GetNullableUlong() { : return ExecuteGetNullable(() => { : return 0ul; : }); : } : 查了一下 string 是 class、ulong 是 struct,所以 type constraint 不符合 : 那有沒有辦法讓這個 generic function 同時接受 class? 跟 struct? : 急 : 在線等 1.包一層 public class foo<T>{ public T value; public bool isnNull; } static foo<T> ExecuteGetNullable<T>(Func<T> func) { ... } 2.改成用 default ExecuteGetNullable -> ExecuteOrDefault catch{ return default(T); } 我記得可以直接拿來比對 if(ExecuteOrDefault() == default(T)) { ... } 我只想到這些 -- Zoosewu Yoututbe顯示PTT推文 可以在各個網站追實況或Live時使用 預覽圖: https://i.imgur.com/ZhtXdAJ.png
https://i.imgur.com/WqbLNV3.png
完整介紹: https://github.com/zoosewu/PTTChatOnYoutube/tree/master/homepage 支援的網站: Youtube Twitch Holotools Niji-mado Holodex -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.229.33 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1694927698.A.65A.html ※ 編輯: ZooseWu (114.32.229.33 臺灣), 09/17/2023 13:15:44

09/17 13:15, 2年前 , 1F
大師
09/17 13:15, 1F

09/17 13:15, 2年前 , 2F
大師
09/17 13:15, 2F

09/17 13:15, 2年前 , 3F
大師
09/17 13:15, 3F

09/17 13:16, 2年前 , 4F
大師
09/17 13:16, 4F

09/17 13:17, 2年前 , 5F
大師ts可以直接用typeof string | number
09/17 13:17, 5F

09/17 13:17, 2年前 , 6F
你就繼續寫扣不跳傘
09/17 13:17, 6F

09/17 13:18, 2年前 , 7F
幹推錯 後面多的 但我是想問ts 可以這樣寫 原來 c#
09/17 13:18, 7F

09/17 13:18, 2年前 , 8F
不行OAO
09/17 13:18, 8F
js是動態語言才能這樣寫 我之前不知道環境還是專案設定有問題 想學ts弄了一個專案 可是我亂寫他都沒報錯 沒定義類型之類的它也不管我 只變成any 害我寫來寫去都好像js

09/17 13:19, 2年前 , 9F
大師
09/17 13:19, 9F

09/17 13:21, 2年前 , 10F
大師
09/17 13:21, 10F
※ 編輯: ZooseWu (114.32.229.33 臺灣), 09/17/2023 13:24:43

09/17 13:28, 2年前 , 11F
大師
09/17 13:28, 11F

09/17 13:31, 2年前 , 12F
謝啦,看來第一個方法比較可行,第二個會回 default
09/17 13:31, 12F

09/17 13:32, 2年前 , 13F
value 很難驗證結果是有錯誤還是真的是 default value
09/17 13:32, 13F

09/17 13:56, 2年前 , 14F
原來是這樣
09/17 13:56, 14F
文章代碼(AID): #1b1ejIPQ (Marginalman)
文章代碼(AID): #1b1ejIPQ (Marginalman)