C#委托代码记录

using System;

using System.Collections.Generic;

using System.Linq;

using System.Security.AccessControl;

using System.Text;

using System.Threading.Tasks;

namespace 委托

{

public delegate void DelSayHollo(string name);

//DelSayHollo 是一个委托类型,表示可以指向任何接受一个 string 参数且返回 void 的方法

internal class Program

{

static void Main(string[] args)

{

//DelSayHollo del=new DelSayHollo (ChineseSayHollo);

DelSayHollo del = ChineseSayHollo; // 实例化委托

del("张三"); // 调用委托

Test("李四", EnglishSayHollo); //方法作为参数传给委托// 将EnglishSayHollo 方法作为参数传递给 Test 方法

Console.ReadKey();

}

public static void Test(string name,DelSayHollo del)// 定义一个方法,接受 DelSayHollo 委托作为参数

{

del(name);

}

public static void ChineseSayHollo(string name)// 定义一个方法,符合 DelSayHollo 委托的签名

{

Console.WriteLine("你好:"+name);

}

public static void EnglishSayHollo(string name) // 定义一个方法,符合 DelSayHollo 委托的签名

{

Console.WriteLine("Ness to meet you" + name);

}

}

}

------------- -------------------- ------------------

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace delegateAnimalPlay

{

internal class Program

{//定义委托

delegate void AnimalPlay(string name);//委托声明 AnimalPlay

static void Main(string[] args)

{

AnimalPlay deleDogPlay = new AnimalPlay(DogPlay); //把函数 DogPlay()转换为 AnimalPlay 型委托

//静态方法CircusStart在本类中直接调用,无需实例

CircusStart(deleDogPlay, "Good evening");// 把委托 deleDogPlay 传给函数CircusStart()

Console.ReadKey();

}

static void CircusStart(AnimalPlay animalPlay, string hello)//静态方法 CircusStart 的签名,该方法接受一个 AnimalPlay 委托和一个字符串参数 name

{

Console.WriteLine("女士们,先生们,我们的马戏表演开始了!");

animalPlay(hello); //1----hello接收的是"Good evening"

}

//函数:狗表演

static void DogPlay(string greetings)//2----接收"Good evening"

{

Console.WriteLine("{0},I am Snoopy!", greetings);//greetings接收hello--"Good evening,后面跟 I am Snoopy!"

Console.WriteLine(@" 狗在表演_");

}

//函数:猫表演

static void CatPlay(string greetings)

{

Console.WriteLine("{0},I am Kitty!", greetings);

Console.WriteLine(@" 猫在表演");

}

//函数:狮子表演

static void LionPlay(string greetings)

{

Console.WriteLine("{0},I am Simba!", greetings);

Console.WriteLine(@"狮子在表演 ");

}

}

}

相关推荐
星光一影44 分钟前
PDF工具箱/合并拆分pdf/提取图片
pdf·c#
baivfhpwxf20232 小时前
要在 WPF 中实现数据表对应实体的属性与 UI 控件的双向绑定,并支持修改通知和 UI 自动更新
c#·wpf
秋月的私语3 小时前
代码自动生成文本小工具TextStringizerWpf
c#
葛小白13 小时前
Winform控件:Chart
c#·winform·chart
好望角雾眠12 小时前
第四阶段C#通讯开发-9:网络协议Modbus下的TCP与UDP
网络·笔记·网络协议·tcp/ip·c#·modbus
我是苏苏14 小时前
C#基础:如何从现有类库复制一个新的类库,并且加入解决方案
开发语言·c#
Jackson@ML18 小时前
用Visual Studio Code最新版开发C#应用程序
ide·vscode·c#
她说彩礼65万19 小时前
C# 代理模式
开发语言·c#·代理模式
张人玉1 天前
TCP 的三次握手和四次挥手
网络·tcp/ip·c#
曹牧1 天前
C#:三元运算符
开发语言·c#