[姆咪] C# Generic 大師請盡

看板Marginalman作者 (xXx_5354M3_31M0_xXx)時間2年前 (2023/09/17 12:50), 編輯推噓2(207)
留言9則, 5人參與, 2年前最新討論串1/2 (看更多)
我想寫個 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? 急 在線等 -- https://i.imgur.com/pUTv8OI.jpg
https://i.imgur.com/lApcJec.jpg
https://i.imgur.com/kql2csq.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.71.204 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1694926240.A.51A.html

09/17 12:52, 2年前 , 1F
毒物王這什麼人設
09/17 12:52, 1F

09/17 12:52, 2年前 , 2F
泥板功能越來越多了 這篇還特地上色
09/17 12:52, 2F

09/17 12:54, 2年前 , 3F
你手動上色嗎
09/17 12:54, 3F

09/17 12:56, 2年前 , 4F
手動上ㄉ。之前有個網站可以上色,可是掛掉了
09/17 12:56, 4F

09/17 13:14, 2年前 , 5F
你這方法和struct矛盾了,struct是值型別沒有null
09/17 13:14, 5F

09/17 13:14, 2年前 , 6F
如果你想要通用的話,一個解決方法是把where拿掉,return
09/17 13:14, 6F

09/17 13:14, 2年前 , 7F
null改成return default(T),然後方法改個名字
09/17 13:14, 7F

09/17 13:23, 2年前 , 8F
感謝,但是用default會回傳default value而不是回null
09/17 13:23, 8F

09/17 13:23, 2年前 , 9F
我再朝這個方向看看
09/17 13:23, 9F
文章代碼(AID): #1b1eMWKQ (Marginalman)
文章代碼(AID): #1b1eMWKQ (Marginalman)