[姆咪] C# Generic 大師請盡
看板Marginalman作者nh60211as (xXx_5354M3_31M0_xXx)時間2年前 (2023/09/17 12:50)推噓2(2推 0噓 7→)留言9則, 5人參與討論串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



--
※ 發信站: 批踢踢實業坊(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
09/17 13:14, 5F
→
09/17 13:14,
2年前
, 6F
09/17 13:14, 6F
→
09/17 13:14,
2年前
, 7F
09/17 13:14, 7F
→
09/17 13:23,
2年前
, 8F
09/17 13:23, 8F
→
09/17 13:23,
2年前
, 9F
09/17 13:23, 9F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):