扩展方法
public static class ExtendMethod
{
public static int ToInt32Ext(this string s)
{
return Int32.Parse(s);
}
/// <summary>
/// 实现自己的Foreach扩展方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="action"></param>
public static void ForEach123<T>(this List<T> list, Action<T> action)
{
foreach (T t in list)
action(t);
}
{
public static int ToInt32Ext(this string s)
{
return Int32.Parse(s);
}
/// <summary>
/// 实现自己的Foreach扩展方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="action"></param>
public static void ForEach123<T>(this List<T> list, Action<T> action)
{
foreach (T t in list)
action(t);
}
}
调用:
private void DoExtend()
{
string s = "9";
int i = s.ToInt32Ext();
List<string> ls = new List<string>() { "a", "b", "c" };
ls.ForEach123(ss => MessageBox.Show(ss));
}
被扩展对象:
this 后面,跟的类型
委托定义:
无返回参数 Action<T1,T2.....>
有返回参数 Func< T1,T2,.....R> R 返回类型