C# – 冷知識 (新手)

替 Action/Func Parameter 設置名字

public static void MatchBracket(string value, string bracket, Action<int, int, string> action) { 
    
}

Action/Func 的 parameter 是不可以設置名字的, 只能聲明類型, 對調用的人不友好.

Can you name the parameters in a Func<T> type?

有 2 個方法可以讓它好一些.

1. 用 delegate 聲明

public delegate void Action(int start, int end, string valueInBracket);
public static void MatchBracket(string value, string bracket, Action action)
{

}

雖然在調用的時候依然無法智能提示, 但至少有個地方可以找到.

2. 用 Tuple

public static void MatchBracket1(string value, string bracket, Action<(int Start, int End, string ValueInBracket)> action)
{

}

調用時可以看到提示

缺點就是結構換了. 可能不習慣.

使用的時候要解構 (而且不能直接在 parameter 裏解, 要拿出來才能解), 或者乾脆把它當對象用會更好一些.

MatchBracket1(value, "{}", matchInfo =>
{
    var (start, end, valueInBracket) = matchInfo;
});

 它也不支持寫 params 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章