Action的使用
public delegate string DisplayMessage (string str)
public class TestCustomDelegate { public static void Main() { DisplayMessage messageTarget; if (Environment.GetCommandLineArgs().Length > 1) messageTarget = ShowWindowsMessage; else messageTarget = Console.WriteLine; messageTarget("Hello, World!"); } private static void ShowWindowsMessage(string message) { MessageBox.Show(message); } } 用Action来代替上面的式子
using System;
using System.Windows.Forms;
public class TestAction1
{
public static void Main()
{
Action<string> messageTarget;
if (Environment.GetCommandLineArgs().Length > 1)
messageTarget = ShowWindowsMessage;
else
messageTarget = Console.WriteLine;
messageTarget("Hello, World!");
}
private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}
用action和匿名方法表示
using System; using System.Windows.Forms; public class TestLambdaExpression { public static void Main() { Action<string> messageTarget; if (Environment.GetCommandLineArgs().Length > 1) messageTarget = s => ShowWindowsMessage(s); else messageTarget = s => Console.WriteLine(s); messageTarget("Hello, World!"); } private static void ShowWindowsMessage(string message) { MessageBox.Show(message); } }ForEach 和 ForEach<(Of <(T>)>) 方法都采用 Action<(Of <(T>)>) 委托作为参数。通过使用由委托封装的方法,可以对数组或列表中的每个元素执行操作。此示例使用 ForEach 方法提供说明。
示例下面的示例演示如何使用 Action<(Of <(T>)>) 委托来打印 List<(Of <(T>)>) 对象的内容。在此示例中,使用 Print 方法将列表的内容显示到控制台上。此外,C# 示例还演示如何使用匿名方法将内容显示到控制台上。using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
// Display the contents of the list using the Print method.
names.ForEach(Print);
// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(String name)
{
Console.WriteLine(name);
});
}
private static void Print(string s)
{
Console.WriteLine(s);
}
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/