Func <T>, Action <T>, Predicate <T> usage summary, funcpredicate
I. Basic Knowledge
1. These three are all. Net built-in generic delegation, which is convenient for us to use directly, without the need to make the following definitions when using the delegate.
public delegate string GetName(string bookId);
2. func <T> is a generic delegate with returned values. The format is Func <T1, T2, T .. n, TResult>, T1, T2, T .. N is multiple parameters, and TResult is returned.
3. Ation <T> is a generic delegate without return values. The format is Action <T1, T2, T. N>, T1, T2, T. N.
4. Predicate <T> is a generic delegate with a return value of Bool. It is equivalent to Func <T, bool> and is mainly used for verification and inspection.
Ii. Usage Comprehension
The use of generic delegation is similar to that of abstract methods of the image class. The implementation of business changes is removed from the outside, and the internal program main framework remains unchanged to implement method injection and attribute injection.
With the use of anonymous methods, the external implementation can be further simplified, and a large number of use of the extension methods of Linq can be achieved.
For example, there is a method to determine the validity of the ticket number (in addition to the judgment, but also write LOG, Count, etc.), because each document is different, the judgment logic is also different, demonstration method Injection
// Define public static bool CheckOrderNo (Func <string, bool> fun, string orderNo) {bool re = fun (orderNo); // TODO: Log // TODO: count return re;} // use the anonymous method // determine whether it is an AA ticket (the length is 10, and the first letter is "AA" var result = CheckOrderNo (x => x. length = 10 & x. substring (0, 2 ). toUpper (). equals ("AA"), "AB126552DFD15"); // you can determine whether it is an AD ticket (Length: 16, 6 ~ 10 letters: "ADGH") var result = CheckOrderNo (x => x. length = 16 & x. substring (5, 4 ). toUpper (). equals ("ADGH"), "AB126ADGH552DFD"); // use the common practice public bool CheckAAOrderNo (string orderNo) {return orderNo. length = 10 & amp; orderNo. substring (0, 2 ). toUpper (). equals ("AA")} var result = CheckOrderNo (CheckAAOrderNo, "AB126552DFD15 ");