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

}

}

}

相关推荐
我好喜欢你~26 分钟前
C#---StopWatch类
开发语言·c#
一阵没来由的风4 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
一枚小小程序员哈10 小时前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
Eternity_GQM12 小时前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
cimeo16 小时前
【C 学习】06-算法&程序设计举例
c#
百锦再17 小时前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
WYH2871 天前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#
hqwest1 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
做一位快乐的码农1 天前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
DavieLau1 天前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#