该功能与Action情况基本类似,但增加了参数传入功能。
用Delegate的代码:
using System;
using System.Windows.Forms;
public delegate void DisplayMessage(string message);
public class testTestDelegate
{
public static void Main()
{
DisplayMessage showMethod = DisplayToWindow;
showMethod("ZHANGPS");
}
public static void DisplayToWindow(string strName)
{
MessageBox.Show("Antiquity Way:Hello World," + strName);
}
}
using System.Windows.Forms;
public delegate void DisplayMessage(string message);
public class testTestDelegate
{
public static void Main()
{
DisplayMessage showMethod = DisplayToWindow;
showMethod("ZHANGPS");
}
public static void DisplayToWindow(string strName)
{
MessageBox.Show("Antiquity Way:Hello World," + strName);
}
}
Action<Of T>代码:
using System;
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action<string> showMethod = DisplayToWindow;
showMethod("ZHANGPS");
}
public static void DisplayToWindow(string strName)
{
MessageBox.Show("Action Way:Hello World," + strName);
}
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action<string> showMethod = DisplayToWindow;
showMethod("ZHANGPS");
}
public static void DisplayToWindow(string strName)
{
MessageBox.Show("Action Way:Hello World," + strName);
}
}
更简洁的方法:
using System;
using System.Windows.Forms;
public class testTestDelegate
{
public static void Main()
{
Action<string> showMethod = s =>{ MessageBox.Show("Action Way:Hello World," + s); };
showMethod("ZHANGPS");
}
}
将方法作为参数传递的方法(
委托,类似C++的指针):
using System;
using System.Windows.Forms;
public delegate void DisplayMessage(string message);
public class testTestDelegate
{
public static void Main()
{
InvokeDispaly(DisplayToWindow);
}
public static void InvokeDispaly(DisplayMessage delegateArgs)
{
delegateArgs("ZHANGPS");
}
public static void DisplayToWindow(string strName)
{
MessageBox.Show("Delegate Param Way:Hello World," + strName);
}
}
using System.Windows.Forms;
public delegate void DisplayMessage(string message);
public class testTestDelegate
{
public static void Main()
{
InvokeDispaly(DisplayToWindow);
}
public static void InvokeDispaly(DisplayMessage delegateArgs)
{
delegateArgs("ZHANGPS");
}
public static void DisplayToWindow(string strName)
{
MessageBox.Show("Delegate Param Way:Hello World," + strName);
}
}