針對某個類型,如果我們不想或不能改變其內部,但想為該類型添加方法,我們可以使用擴展方法來實現。如果該類型有更高層次的抽象,比如接口,我們應為更高層次類型編寫擴展方法。另外,擴展方法是鏈式編程的前提。
判斷集合是否包含元素
List<int> list = new List<int>();
if(list != null && list.Count > 0)
{
}
我們可以針對比int類型更高層次的ICollection接口寫一個擴展方法:
public static bool HasElements(this ICollection list)
{
return list != null && list.Count > 0
}
然後可以這樣使用:
List<int> list = new List<int>();
if(list.HasElements())
{
}
判斷一個值是否在2個大小數之間
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;
}
我們可以針對比某個具體類更高層次的IComparable接口寫一個擴展方法:
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;
}
可以這樣使用:
int a = 10; a.IsBetween(1,8);
針對集合中的每一個元素實施相同的方法
List<string> strList = new List<string>();
foreach(var item in strList)
{
SomeMethod(item);
}
首先,可以針對比string更高層次抽象的ICollection編寫擴展方法,其次,遍歷元素執行的方法抽象成一個委托參數。如下:
public static void EachMethod<T>(this ICollection<T> items, Action<T> action)
{
foreach(T item in items)
{
action(item);
}
}
現在可以這樣使用:
List<string> strList = new List<string>();
strList.EachMethod(s => {
Console.WriteLine(s);
});
判斷元素是否包含在集合中
string str = "a";
List<string> strs = new List<string>(){"a", "b"};
if(strs.Contains(str))
{
//TODO:
}
可以針對比string更高層次抽象的泛型類型編寫擴展方法:
public static bool In<T>(this T source, params T[] list)
{
if(source == null) throw new ArgumentNulllException("source");
return list.Contains(source);
}
這樣使用:
string temp = "a";
temp.In("a","b");