FuncT TResult ActionT 和 PredicateT 委託型別
System 名稱空間包含 Func<..., TResult>
委託型別,其中包含 0 到 15 個通用引數,返回型別 TResult
。
private void UseFunc(Func<string> func)
{
string output = func(); // Func with a single generic type parameter returns that type
Console.WriteLine(output);
}
private void UseFunc(Func<int, int, string> func)
{
string output = func(4, 2); // Func with multiple generic type parameters takes all but the first as parameters of that type
Console.WriteLine(output);
}
System 名稱空間還包含具有不同數量的通用引數的 Action<...>
委託型別(從 0 到 16)。它類似於 Func<T1, .., Tn>
,但它總是返回 void
。
private void UseAction(Action action)
{
action(); // The non-generic Action has no parameters
}
private void UseAction(Action<int, string> action)
{
action(4, "two"); // The generic action is invoked with parameters matching its type arguments
}
Predicate<T>
也是 Func
的一種形式,但它總會返回 bool
。謂詞是一種指定自定義條件的方法。根據輸入的值和謂詞中定義的邏輯,它將返回 true
或 false
。因此 Predicate<T>
的行為方式與 Func<T, bool>
相同,並且兩者都可以以相同的方式初始化和使用。
Predicate<string> predicate = s => s.StartsWith("a");
Func<string, bool> func = s => s.StartsWith("a");
// Both of these return true
var predicateReturnsTrue = predicate("abc");
var funcReturnsTrue = func("abc");
// Both of these return false
var predicateReturnsFalse = predicate("xyz");
var funcReturnsFalse = func("xyz");
是否使用 Predicate<T>
或 Func<T, bool>
的選擇實際上是一個意見問題。Predicate<T>
可能更能表達作者的意圖,而 Func<T, bool>
可能對更大比例的 C#開發者很熟悉。
除此之外,在某些情況下,只有一個選項可用,尤其是在與其他 API 互動時。例如 List<T>
和 Array<T>
通常採用 Predicate<T>
作為他們的方法,而大多數 LINQ 擴充套件只接受 Func<T, bool>
。