如何扩展IEnumerator 的 ForEach<T>(Action)方法
其实挺简单,但对于我这水平的人来说,却费了小半天工夫,为啥?对.net的类库太不熟悉!
好了,自我检讨过后,讲述过程并贴出代码:
首先,在您的解决方案中新建一个项目并添加一个新的扩展类,或者在已有项目中添加一个新扩展类也可以,如下图所示(ClassLibrary1即是新添的项目):

新类的代码如下:
希望能给初学者以帮助!
好了,自我检讨过后,讲述过程并贴出代码:
首先,在您的解决方案中新建一个项目并添加一个新的扩展类,或者在已有项目中添加一个新扩展类也可以,如下图所示(ClassLibrary1即是新添的项目):

新类的代码如下:
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
6
namespace ClassLibrary1
7
{
8
public static class EnumerExtension
9
{
10
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) {
11
if (action != null)
12
{
13
int eCount = enumerable.Count();
14
for (int i = 0; i < eCount; i++)
15
{
16
action(enumerable.ElementAt(i));
17
}
18
}
19
}
20
}
21
}
代码很少,但我却Reflection了不少类库,比如mscorlib.dll,唉,最终还是如此简短的几行。
using System;2
using System.Collections.Generic;3
using System.Linq;4
using System.Text;5

6
namespace ClassLibrary17
{8
public static class EnumerExtension9
{ 10
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) {11
if (action != null)12
{13
int eCount = enumerable.Count();14
for (int i = 0; i < eCount; i++)15
{16
action(enumerable.ElementAt(i));17
}18
}19
}20
}21
}希望能给初学者以帮助!


浙公网安备 33010602011771号