您的位置:首页 > 编程语言 > C#

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

2015-01-30 23:34 441 查看
    最近对扩展方法比较感兴趣,就看了看资料,记录一下扩展方法的几种方法.

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

    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);
}
}


      

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: