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(@"狮子在表演 ");

}

}

}

相关推荐
嵌入式学习和实践1 小时前
C# WinForms 多窗口交互通信的示例-主窗口子窗口交互通信
c#·交互·主窗口-子窗口通信
专注VB编程开发20年1 小时前
C#,VB.NET数组去重复,提取键名和重复键和非重复键
c#·.net·linq·取唯一键·去重复·重复数量
YuanlongWang2 小时前
Entity Framework Core和SqlSugar的区别,详细介绍
c#
unicrom_深圳市由你创科技5 小时前
工业上位机,用Python+Qt还是C#+WPF?
python·qt·c#
偶尔的鼠标人15 小时前
Avalonia DataGrid 控件的LostFocus事件会多次触发
开发语言·c#
ytttr87316 小时前
C# 仿QQ聊天功能实现 (SQL Server数据库)
数据库·oracle·c#
future_studio18 小时前
聊聊 Unity(小白专享、C# 小程序 之 图片播放器)
unity·小程序·c#
c#上位机1 天前
wpf中Grid的MouseDown 事件无法触发的原因
c#·wpf
CodeCraft Studio1 天前
国产化PDF处理控件Spire.PDF教程:如何在 C# 中从 HTML 和 PDF 模板生成 PDF
pdf·c#·html·.net·spire.pdf·pdf文档开发·html创建模板pdf
ysdysyn1 天前
.NET 10深度解析:性能革新与开发生态的全新篇章
c#·.net