最近對擴展方法比較感興趣,就看了看資料,記錄一下擴展方法的幾種方法.
一. 擴展方法的基本使用:
Note: 1. 擴展方法必須在靜態類中, 2 擴展方法必須聲明靜態方法,3 擴展方法裡面不能調用其他自定義方法。
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;
}
二. 擴展方法之泛型: 上面都是對擴展方法的類型寫死了,擴展方法一樣支持泛型:
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;
}
三. 泛型方法之委托: 泛型方法可以支持委托,跟方便我們對數據的操作,下面來模擬集合的foreach方法.
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}