显然有许多方法可以迭代集合。很好奇是否有什么不同,或者为什么你用一种方式而不是另一种。
第一类型:
List<string> someList = <some way to init>
foreach(string s in someList) {
<process the string>
}
其他方式:
List<string> someList = <some way to init>
someList.ForEach(delegate(string s) {
<process the string>
});
我想,除了我上面使用的匿名委托,你还可以指定一个可重用的委托。
ForEach函数是泛型类List的成员。
我已经创建了以下扩展来复制内部代码:
public static class MyExtension<T>
{
public static void MyForEach(this IEnumerable<T> collection, Action<T> action)
{
foreach (T item in collection)
action.Invoke(item);
}
}
因此,最后我们使用普通的foreach(如果你愿意,也可以使用循环for)。
另一方面,使用委托函数只是定义函数的另一种方式,以下代码:
delegate(string s) {
<process the string>
}
等价于:
private static void myFunction(string s, <other variables...>)
{
<process the string>
}
或者使用labda表达式:
(s) => <process the string>
ForEach函数是泛型类List的成员。
我已经创建了以下扩展来复制内部代码:
public static class MyExtension<T>
{
public static void MyForEach(this IEnumerable<T> collection, Action<T> action)
{
foreach (T item in collection)
action.Invoke(item);
}
}
因此,最后我们使用普通的foreach(如果你愿意,也可以使用循环for)。
另一方面,使用委托函数只是定义函数的另一种方式,以下代码:
delegate(string s) {
<process the string>
}
等价于:
private static void myFunction(string s, <other variables...>)
{
<process the string>
}
或者使用labda表达式:
(s) => <process the string>