For a type, if we do not want to or cannot change it, but want to add a method for this type, we can use the extension method. If this type has a higher level of abstraction, such as an interface, we should compile an extension method for a higher level type. In addition, the extension method is the premise of chain programming.
Determine whether a set contains elements
List<int> list = new List<int>();if(list != null && list.Count > 0){ }
We can write an extension method for the ICollection interface at a higher level than the int type:
public static bool HasElements(this ICollection list){ return list != null && list.Count > 0}
Then you can use it like this:
List<int> list = new List<int>();if(list.HasElements()){ }
Determines whether a value is between two decimal places.
public class A : IComparable{}public class B : IComparable{}public class C : IComparable{}public bool IsBetween(A a, B b, C c){ return a.CompareTo(b) >=0 && c.CompareTo(c) <= 0;}
We can write an extension method for the IComparable interface higher than a specific class:
public static bool IsBetween<T>(this T value, T min, T max) where T : IComparable<T>{ return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0;}
It can be used as follows:
int a = 10;a.IsBetween(1,8);
Implement the same method for each element in the Set
List<string> strList = new List<string>();foreach(var item in strList){ SomeMethod(item);}
First, you can write extension methods for icollections that are more abstract than string. Second, the methods executed by traversal elements are abstracted into a delegate parameter. As follows:
public static void EachMethod<T>(this ICollection<T> items, Action<T> action){ foreach(T item in items) { action(item); }}
You can use the following code:
List<string> strList = new List<string>();strList.EachMethod(s => { Console.WriteLine(s);});
Determine whether an element is included in a collection
string str = "a";List<string> strs = new List<string>(){"a", "b"};if(strs.Contains(str)){ //TODO:}
You can write extension methods for generic types that are more abstract than string:
public static bool In<T>(this T source, params T[] list){ if(source == null) throw new ArgumentNulllException("source"); return list.Contains(source);}
This method is used as follows:
string temp = "a";temp.In("a","b");