System.Action委托(C# 3.5+)
Action:相当于一种无参数传递的委托,从Framework 3.5开始加如,简化了委托调用代码:
Delegate原代码:
using System;
using System.Windows.Forms;
public delegate void DisplayMessage();
public class testTestDelegate
{
public static void Main()
{
DisplayMessage showMethod = DisplayToWindow();
showMethod();
}
public static void DisplayToWindow()
{
MessageBox.Show("Antiquity Way:Hello World");
}
using System.Windows.Forms;
public delegate void DisplayMessage();
public class testTestDelegate
{
public static void Main()
{
DisplayMessage showMethod = DisplayToWindow();
showMethod();
}
public static void DisplayToWindow()
{
MessageBox.Show("Antiquity Way:Hello World");
}
}
Action新代码:
using System;
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action showMethod = DisplayToWindow;
showMethod();
}
public static void DisplayToWindow()
{
MessageBox.Show("Action Way:Hello World");
}
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action showMethod = DisplayToWindow;
showMethod();
}
public static void DisplayToWindow()
{
MessageBox.Show("Action Way:Hello World");
}
}
更简洁的方法:(Lambda方法)
using System;
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action showMethod = () =>{ MessageBox.Show("Action Way:Hello World"); };
showMethod();
}
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action showMethod = () =>{ MessageBox.Show("Action Way:Hello World"); };
showMethod();
}
}
参考MSDN:http://msdn.microsoft.com/zh-cn/library/system.action.aspx