This article analyzes the usage of Predicate<T> and Func<T, bool> generic delegation in C# in example form, and shares it with you for your reference. The details are as follows:
Let’s take a look at the following example:
static void Main(string[] args) { List<string> l = new List<string>(); ("a"); ("b"); ("s"); ("t"); if ((s => ("s"))) { string str = (s => ("s")); (str); } else ("Not found"); }
It is very simple, first determine whether there is an s string in the string list l. If so, take it and display it. As you can see from the code, the parameters used by the method and method are the same, but is this true?
In fact, the parameters of List<T>.Exists and List<T>.First use different delegates:
Predicate<T> and Func<T, bool>. Judging from the function signature, there is no difference between the two. Both refer to functions with parameter type T and return value bool, but after all, the two belong to different delegate types, so the following code is obviously unable to compile and pass:
static void Main(string[] args) { List<string> l = new List<string>(); ("a"); ("b"); ("s"); ("t"); Func<string, bool> p = s => ("s"); if ((p)) { string str = (p); (str); } else ("Not found"); }
However, since Predicate<T> and Func<T, bool> do refer to functions with the same class with the same signature, and we often do not want to repeatedly write the method body of an anonymous method twice to assign the Predicate<T> and Func<T, bool> generic delegates respectively, we can write an extension method ourselves, extending the Func<T, bool> type to make it convenient to convert it to the Predicate<T> type:
public static class Extensions { public static Predicate<T> ToPredicate<T> (this Func<T, bool> source) { Predicate<T> result = new Predicate<T>(source); return result; } }
After introducing this extension method, our code can be written in the following form:
static void Main(string[] args) { List<string> l = new List<string>(); ("a"); ("b"); ("s"); ("t"); Func<string, bool> p = s => ("s"); if ((())) { string str = (p); (str); } else ("Not found"); }
To be honest, somehow MS uses two completely different generic delegates to implement Exists and First methods, which makes the code relatively complex and even prone to errors in some cases. I think it is probably for the sake of semantic clarity, Exists are just making judgments, so assertion expressions are needed. When doing the First operation, it is more of a sense that the specified method is called iteratively. Learning is endless and needs to be explored.
I hope this article will be helpful to everyone's C# programming