C#中的委托、委托链、匿名函数、lamda表达式、事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
//声明委托
public delegate void SayHellowdlg(string name);
class Program
{
//创建一个SayHellowdlg类型的事件
public static event SayHellowdlg SayHellowEvent;
static void Main(string[] args)
{
//实例化委托
SayHellowdlg say = SayHellow;
say("张三");
Console.WriteLine("****************以上是调用委托******************");
//委托链
say += SayGoodBye;
say("张三");
Console.WriteLine("****************以上是委托链******************");
//匿名函数
SayHellowdlg say2 = delegate (string name)
{
Console.WriteLine($"{name},这是一个匿名函数");
};
say2("李四");
Console.WriteLine("****************以上是匿名函数******************");
//lamda 语句
SayHellowdlg say3 = (name) =>
{
Console.WriteLine($"{name},这是一个lamda语句");
};
say3("王五");
Console.WriteLine("****************以上是lamda语句******************");
//事件
SayHellowEvent += Program_SayHellowEvent;
if (SayHellowEvent !=null)
{
SayHellowEvent("赵六");
}
Console.WriteLine("****************以上是调用事件******************");
Console.ReadKey();
}

private static void Program_SayHellowEvent(string name)
{
Console.WriteLine($"{name},这是一个事件");
}

public static void SayHellow(string name)
{
Console.WriteLine($"{name},你好啊!");
}
public static void SayGoodBye(string name)
{
Console.WriteLine($"{name},再见啊!");
}
}
}

posted @ 2020-08-18 15:05  夜半钟声Pro  阅读(48)  评论(0)    收藏  举报