C#基础---扩展方法的应用
2015-01-30 23:34
531 查看
最近对扩展方法比较感兴趣,就看了看资料,记录一下扩展方法的几种方法.
一. 扩展方法的基本使用:
Note: 1. 扩展方法必须在静态类中, 2 扩展方法必须声明静态方法,3 扩展方法里面不能调用其他自定义方法。
二. 扩展方法之泛型: 上面都是对扩展方法的类型写死了,扩展方法一样支持泛型:
三. 泛型方法之委托: 泛型方法可以支持委托,跟方便我们对数据的操作,下面来模拟集合的foreach方法.
一. 扩展方法的基本使用:
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); } }
相关文章推荐
- c# 扩展方法奇思妙用高级篇三:Enumerable.Cast<T> 应用
- c# 扩展方法奇思妙用基础篇四:Random 扩展
- [C# 基础知识系列] 专题十五:全面解析扩展方法
- c# 扩展方法奇思妙用基础篇七:IsBetween 通用扩展
- [C# 基础知识系列] 专题十五:全面解析扩展方法
- c#扩展方法奇思妙用基础篇二:string 常用扩展
- C#的扩展方法应用
- [C# 基础知识系列]专题十五:全面解析扩展方法
- C# 扩展方法实际应用整理
- c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展
- c#扩展方法奇思妙用高级篇三:Enumerable.Cast<T>应用
- 不可不知的C#基础应用+--+Extension+扩展方法
- c#扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展
- C#基础:通过一个实例来学习IFormattable接口,扩展方法
- Linq的那些事——从Linq扩展方法回顾C#语言基础
- C#扩展方法的应用
- c# 扩展方法奇思妙用基础篇九:Expression 扩展
- 不可不知的C#基础 1. -- Extension 扩展方法
- c# 扩展方法奇思妙用基础篇二:string 常用扩展
- C#基础:通过一个实例来学习IFormattable接口,扩展方法