C # basics-Application of extension methods,
Recently I was interested in the extension method. I looked at the information and recorded several methods of the extension method.
I. basic use of the extension method:
Note: 1. Extension methods must be in static classes. 2 extension methods must declare static methods. 3 extension methods cannot call other custom methods.
public static int TryToInt(this string intStr) { int number = 0; int.TryParse(intStr, out number); return number; }public static IEnumerable<string> StartsWith(this IEnumerable<string> ie, string startStr) { IEnumerable<string> returnIe = null; if (ie != null) { returnIe = ie.Where(x => x.StartsWith(startStr)); } return returnIe; }
Ii. Extension Method generics: The above are all types of extension methods written to death, extension methods support generics as well:
public static bool IsBetween<T>(this T value, T low, T high) where T : IComparable<T> { return value.CompareTo(low) >= 0 && value.CompareTo(high) < 0; }
Iii. Delegation of generic methods: the generic method supports delegation, which facilitates data operations. The foreach method of the set is simulated below.
public static void Each<T>(this IEnumerable<T> items, Action<T> action) { foreach (T item in items) { action(item); } }