C#基础---扩展方法的应用

时间:2023-03-09 20:27:45
C#基础---扩展方法的应用

    最近对扩展方法比较感兴趣,就看了看资料,记录一下扩展方法的几种方法.

   一. 扩展方法的基本使用:

    Note: 1. 扩展方法必须在静态类中, 2 扩展方法必须声明静态方法,3 扩展方法里面不能调用其他自定义方法。

public static int TryToInt(this string intStr)
{
int number = ;
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);
}
}