C # How to Use delegate to implement the Javascript each method,
C # contains many confusing keywords, such as delegate, Func, Action, and Predicate. Func, Action, and Predicate are essentially delegate. Let's take a look at the delegate concept.
1. delegate Concept
Delegate is essentially a pointer to a function. It can point to different functions, as long as the signature of the function is consistent with that of the proxy.
2. delegate Application
In fact, Func, Action, and Predicate are all delegate, but they are only special delegate. The clever application of delegate can greatly simplify code and improve flexibility. Below is a piece of Javascript code. JS often uses the array each method to traverse the array and process it, as shown below:
1 var arr = ["one", "two", "three", "four"]; 2 $. each (arr, function () {3 alert (this); 4}); 5 // The above each Outputs one, two, three, and four respectively.
In C #, how can we use delegate to define an array each method? We can use an input method to implement flexible logic processing. There is a static Each method in the static ListEx class, definition:
1 public static T[] Each<T>(T[] source, Func<T, T> function) 2 { 3 4 T[] ret =new T[source.Length]; 5 int i = 0; 6 foreach (T item in source) 7 { 8 ret[i]=function(item); 9 i++;10 }11 return ret;12 }
Then we can define a string array and define a delegate as the function parameter for input. Call the ListEx. Each method:
1 var arr =new string[]{ "one", "two", "three", "four"}; 2 var newArr= ListEx.Each<string>(arr,delegate(string x){3 x=x+"_do";4 return x;5 });
Of course, you can use expressions to simplify the process:
1 var newArr2 = ListEx.Each<string>(newArr, (string x) => x = x + "_do");
We can also define a Where method to Filter Arrays:
1 public static IList<T> Find<T>(IList<T> source, Predicate<T> predicate) 2 { 3 List<T> ret = new List<T>(); 4 foreach (T item in source) 5 { 6 if (predicate(item)) 7 { 8 ret.Add(item); 9 }10 }11 return ret;12 }13 public static T[] Where<T>(T[] source, Predicate<T> predicate)14 {15 IList<T> list=source.ToList<T>();16 IList<T> retList= Find<T>(list, predicate);17 return retList.ToArray<T>();18 }
The call is as follows:
1 var newArr3 = ListEx.Where<string>(arr, x => x == "two");
3 Differences
Func is a proxy that must specify the returned value;
Action is the proxy whose return value is void;
Predicate is the proxy whose return value is bool;