[C#] Action
delegate Code Sample
===== Just delegate =====
using System;
using System.Windows.Forms;
delegate void DisplayMessage(string message);
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 with anonymous methods ====
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); };
messageTarget("Hello, World!");
}
private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}
==== Lambda expression to an 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);
}
}