譯文鏈接:https://www.infoworld.com/article/3057152/how-to-work-with-action-func-and-predicate-delegates-in-csharp.html?nsdr=true
委託是一個類型安全的函數指針,它可以引用與委託具有相同簽名的方法。委託常用於實現回調方法或者事件機制,在C#中一般用 "delegate" 關鍵字聲明。你可以聲明一個和類平級的委託,也可以嵌套在類中。
Func 和 Action 是什麼,如何使用?
兩者最基本的區別是,前者適合那些需要帶返回值的委託,後者適合那些不帶返回值的委託。
Func 所引用的方法接收一個或者多個入參並帶有一個返回值,Action所引用的方法接收一個或者多個參數並且沒有返回值,換句話說,你的委託所引用的方法沒有返回值,這時候適合用 Action。
Predicate所引用的方法接收一個或者多個泛型參數並且返回一個 bool 值,你可以假定它等價於 Func<T,bool>
,Predicate 常用於對 collection 進行一組條件檢索。
C# 中使用 Action
你可以使用 委託 去實現事件和回調方法,C#委託非常類似於C++中的函數指針,但是 C# 中的 委託 是類型安全的,你可以將方法作爲參數傳遞給委託從而讓委託指向該方法。
下面的代碼片段展示了 Action 委託的語法結構。
Action<TParameter>
接下來的代碼清單展示瞭如何使用 Action 委託,當下面的代碼執行結束後會在控制檯打印 Hello !!!
。
static void Main(string[] args)
{
Action<string> action = new Action<string>(Display);
action("Hello!!!");
Console.Read();
}
static void Display(string message)
{
Console.WriteLine(message);
}
C# 中使用 Func
現在我們一起學習下 Func 委託,下面是 Func 的語法結構。
Func<TParameter, TOutput>
接下來的代碼片段展示瞭如何在 C# 中使用 Func 委託,最終方法會打印出 Hra(基本薪資的 40%) 的值,基本薪資是作爲參數傳下去的,如下代碼所示:
static void Main(string[] args)
{
Func<int, double> func = new Func<int, double>(CalculateHra);
Console.WriteLine(func(50000));
Console.Read();
}
static double CalculateHra(int basic)
{
return (double)(basic * .4);
}
值得注意的是,Func 委託的第二個參數表示方法的返回值,在上面這個例子中,它就是計算後的 Hra 值,作爲 double 型返回。
C# 中使用 Predicate
Predicate 委託常用於檢索 collection,下面是 Predicate 的語法結構。
Predicate<T>
值得注意的是, Predicate<T>
差不多等價於 Func<T,bool>
。
考慮下面的 Customer 實體類。
class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
接下來生成一個 customer 集合並且丟一些數據進去,如下代碼:
List<Customer> custList = new List<Customer>();
custList.Add(new Customer { Id = 1, FirstName = "Joydip", LastName = "Kanjilal", State = "Telengana", City = "Hyderabad", Address = "Begumpet", Country = "India" });
custList.Add(new Customer { Id = 2, FirstName = "Steve", LastName = "Jones", State = "OA", City = "New York", Address = "Lake Avenue", Country = "US" });
接下來是完整的代碼片段展示瞭如何使用 Predicate 去檢索集合。
static void Main(string[] args)
{
List<Customer> custList = new List<Customer>();
custList.Add(new Customer { Id = 1, FirstName = "Joydip", LastName = "Kanjilal", State = "Telengana", City = "Hyderabad", Address = "Begumpet", Country = "India" });
custList.Add(new Customer { Id = 2, FirstName = "Steve", LastName = "Jones", State = "OA", City = "New York", Address = "Lake Avenue", Country = "US" });
Predicate<Customer> hydCustomers = x => x.Id == 1;
Customer customer = custList.Find(hydCustomers);
Console.WriteLine(customer.FirstName);
Console.Read();
}
當上面的代碼被成功執行, 控制檯將會輸出 Joydip
。