Re: [姆咪] C# Generic 大師請盡
※ 引述《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://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
09/17 13:17, 5F
噓
09/17 13:17,
2年前
, 6F
09/17 13:17, 6F
→
09/17 13:18,
2年前
, 7F
09/17 13:18, 7F
→
09/17 13:18,
2年前
, 8F
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
09/17 13:31, 12F
→
09/17 13:32,
2年前
, 13F
09/17 13:32, 13F
→
09/17 13:56,
2年前
, 14F
09/17 13:56, 14F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):