扩展函数
- 实现IEnumerable接口
public IEnumerator<int> GetEnumerator()
{
//throw new NotImplementedException();
yield return 1;
yield return 2;
yield return 3;
yield return 4;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
2 扩展方法的使用
- 扩展方法的类型以及类名都是静态的,提供外部调用,等于是一个全局类
- 给指定的类扩展需要使用this关键字指定 参数就是类
代码案例如下:
/*
*
* 扩展方法 使用this -->指代那个实例化对象扩展方法
*/
static class MyExMethods
{
public static int MyMax(this MyList list)
{
int max = int.MinValue;
var e = list.GetEnumerator();
while (e.MoveNext())
{
if (e.Current > max)
{
max = e.Current;
}
}
return max;
}
public static int MyCount(this MyList vs)
{
int sum = 0;
var list = vs.GetEnumerator();
/*foreach (var i in list.MoveNext())
{
sum++;
}*/
while (list.MoveNext())
{
sum++;
}
return sum;
}
public static void ForEach<T>(this IEnumerable<T> source,Action<T> func)
{
foreach(var item in source)
{
func(item);
}
}
public static void Print<T>(this IEnumerable<T> ts)
{
foreach (var item in ts)
{
Console.WriteLine(item);
}
}
//字符串转换
public static int ToInt(this string s)
{
return int.Parse(s);
}
}
}