Action的使用
Action<T> Delegate
概述:Encapsulates a method that has a single parameter and does not return a value.
描述:You can use the
Action<T>
delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value. (In C#, the method must return
void
.
Typically, such a method is used to perform an operation.
个人理解:
- 用一种更简洁的方式创建委托
- 作为IEnumerable<T>某些方法的参数,例如Forecach,
- 创建Acton实例可以用传统的委托方法,也可以用Lambda表达式,当然很多时候是我们可以不显示创建一个Action,但实际上我们要知道,创建的是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);
}
}
使用委托以及Lambda的方式:
using System;
using System.Windows.Forms;
public class TestAnonMethod
{
public static void Main()
{
Action<string> messageTarget;
//委托
if (Environment.GetCommandLineArgs().Length > 1)
messageTarget = delegate(string s) { ShowWindowsMessage(s); };
else
messageTarget = delegate(string s) { Console.WriteLine(s); };
//Lambda
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);
}
}