c#委托把方法当成参数(实例讲解)
本文导语: 静态方法代理: 代码如下:public delegate void DoGreeting(string name); class Program { [STAThread] static void Main(string[] args) { //方法名当成参数传给委托类型调用 MarkGreeting(...
静态方法代理:
public delegate void DoGreeting(string name);
class Program
{
[STAThread]
static void Main(string[] args)
{
//方法名当成参数传给委托类型调用
MarkGreeting("张三", GreetingEnglish);
MarkGreeting("李四", GreetingChinese);
}
///
/// 委托(代理的方法)
///
///
///
private static void MarkGreeting(string name, DoGreeting markGreeting)
{
markGreeting(name);
}
///
/// 用英文打招呼
///
///
private static void GreetingEnglish(string name)
{
Console.WriteLine(name+"hello!");
}
///
/// 用中文打招呼
///
///
private static void GreetingChinese(string name)
{
Console.WriteLine(name+"你好!");
}
}
实例方法代理:
public delegate void DoGreeting(string name);
public class Greeting
{
///
/// 委托(代理的方法)
///
///
///
public void MarkGreeting(string name, DoGreeting markGreeting)
{
markGreeting(name);
}
///
/// 用英文打招呼
///
///
public void GreetingEnglish(string name)
{
Console.WriteLine(name + "hello!");
}
///
/// 用中文打招呼
///
///
public void GreetingChinese(string name)
{
Console.WriteLine(name + "你好!");
}
}
class Program
{
[STAThread]
static void Main(string[] args)
{
Greeting greetingObj = new Greeting();
greetingObj.MarkGreeting("张三", greetingObj.GreetingEnglish);
greetingObj.MarkGreeting("李四", greetingObj.GreetingChinese);
}