我看到有人写:
//wordList is List<string>
wordList.ForEach(delegate(string word){ Console.WriteLine(word);});
代替:
foreach(string word in wordList)
{
Console.WriteLine(word);
}
这样做有什么好处。尽管我在 C# 2.0 中使用过委托(delegate),但我也无法理解上面给出的 Action 委托(delegate)语法。基本上我无法将语法与我熟悉的委托(delegate)概念联系起来。 你能帮我理解语法吗?是简写吗?
最佳答案
delegate() {...}
语法在 .NET 2 中可用。它实质上是在包含委托(delegate)内容的包含类中创建一个(匿名)方法。所以,上面的语法等同于
private void actionImpl(string word) {
Console.WriteLine(word);
}
wordList.ForEach(new Action<string>(actionImpl));
关于 List<T>.ForEach
, Eric Lippert has blogged about this .当一个 Action 没有副作用并且是一个非常简单的单行时,它很有用。使用隐式委托(delegate)创建和方法组,您可以将代码示例缩减为
wordList.ForEach(Console.WriteLine);
作为Console.WriteLine(string s)
匹配Action<string>
代表签名。这比使用显式 foreach
代码更少,而且(我认为)更清晰循环,在这个特定的例子中。
关于c# - 使用委托(delegate)表示法访问通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2526587/