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

}

}

}

相关推荐
阿伍.2 小时前
【指针】(适合考研、专升本)
c++·考研·c#
香煎三文鱼2 小时前
C# net8生成excel,并设置列规则导出文件
c#·excel·c#生成ecel
汪小白JIY3 小时前
【C#】多级缓存与多核CPU
缓存·c#·多级缓存
工程师0074 小时前
C#AES加密
网络·安全·web安全·c#
程序设计实验室6 小时前
提升Avalonia UI质感,跨平台图标库选型实践
c#·avalonia
我是苏苏9 小时前
C#高级:利用反射让字符串决定调用哪个方法
后端·c#
月巴月巴白勺合鸟月半14 小时前
工作记录 2017-08-01
c#·健康医疗
Rose 使者19 小时前
全网手机二次放号查询接口如何用C#进行调用?
c#·api·手机二次放号
Rose 使者21 小时前
全国天气预报查询接口如何用C#进行调用?
c#·api·天气预报