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 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修1 小时前
c#中public类比博图
c#·自动化
土了个豆子的3 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
xiaowu08021 小时前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful1 天前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide1 天前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_22991 天前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty271 天前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机1 天前
wpf之TextBlock
c#·wpf
almighty272 天前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页