c#委托把方法当成参数(实例讲解)

时间:2021-05-20

静态方法代理:
复制代码 代码如下:
public delegate void DoGreeting(string name);

class Program
{
[STAThread]
static void Main(string[] args)
{
//方法名当成参数传给委托类型调用
MarkGreeting("张三", GreetingEnglish);
MarkGreeting("李四", GreetingChinese);
}

/// <summary>
/// 委托(代理的方法)
/// </summary>
/// <param name="name"></param>
/// <param name="markGreeting"></param>
private static void MarkGreeting(string name, DoGreeting markGreeting)
{
markGreeting(name);
}

/// <summary>
/// 用英文打招呼
/// </summary>
/// <param name="name"></param>
private static void GreetingEnglish(string name)
{
Console.WriteLine(name+"hello!");
}

/// <summary>
/// 用中文打招呼
/// </summary>
/// <param name="name"></param>
private static void GreetingChinese(string name)
{
Console.WriteLine(name+"你好!");
}
}

实例方法代理:
复制代码 代码如下:
public delegate void DoGreeting(string name);

public class Greeting
{
/// <summary>
/// 委托(代理的方法)
/// </summary>
/// <param name="name"></param>
/// <param name="markGreeting"></param>
public void MarkGreeting(string name, DoGreeting markGreeting)
{
markGreeting(name);
}

/// <summary>
/// 用英文打招呼
/// </summary>
/// <param name="name"></param>
public void GreetingEnglish(string name)
{
Console.WriteLine(name + "hello!");
}

/// <summary>
/// 用中文打招呼
/// </summary>
/// <param name="name"></param>
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);

}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章