Func<T1, T2, ..., TResult> là delegate generic đại diện cho phương thức có trả về giá trị (khác với Action trả về void). Có từ 0 đến 16 tham số đầu vào, tham số cuối cùng là kiểu trả về.
Các ví dụ Func với số tham số khác nhau
// 1 tham số int → string
Func one = p => string.Format("{0}", p);
// 2 tham số (bool, long) → string
Func two = (q, p) => string.Format("{0} and {1}", q, p);
// 2 tham số (bool, int) → string
Func three = (q, p) => string.Format("{0} and {1}", q, p);
// 1 tham số decimal → string
Func four = p => string.Format("{0}", p);
Mã nguồn hoàn chỉnh
using System;
using System.IO;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
// 1 tham số int → string
Func one = p => string.Format("{0}", p);
// 2 tham số bool, long → string
Func two = (q, p) => string.Format("{0} and {1}", q, p);
// 2 tham số bool, int → string
Func three = (q, p) => string.Format("{0} and {1}", q, p);
// 1 tham số decimal → string
Func four = p => string.Format("{0}", p);
Console.WriteLine(one.Invoke(25)); // 25
Console.WriteLine(two.Invoke(false, 76756566)); // False and 76756566
Console.WriteLine(three.Invoke(true, 50)); // True and 50
Console.WriteLine(four.Invoke(1.2m)); // 1.2
}
}
}
Kết quả
25
False and 76756566
True and 50
1.2
Các biến thể Func
| Delegate | Tham số nhập | Trả về |
Func | 0 | TResult |
Func | 1 | TResult |
Func | 2 | TResult |
| ... | ... | ... |
Func | 16 | TResult |
Func vs Action vs Predicate
| Delegate | Trả về | Dùng cho |
Func<..., TResult> | TResult | Tính toán, mapping, transformation |
Action<...> | void | Side effect (log, write, modify) |
Predicate<T> | bool | Filter, condition check |
Ứng dụng thực tế
- Strategy pattern:
Func processor
- Factory:
Func creator
- LINQ selectors:
Select(Func), Where(Func) (Predicate)
- Callback với kết quả trả về
- Memoization, caching