C# 委托及匿名函数

一、 为什么使用委托,代码如下;(注释掉的是没用委托之前的使用方式,没有注释的是使用了委托的

                   

复制代码
  public delegate string DelProStr(string name);
class Program
{
static void Main(string[] args)
{
//三个需求
//1、将一个字符串数组中每个元素都转换成大写
//2、将一个字符串数组中每个元素都转换成小写
//3、将一个字符串数组中每个元素两边都加上 双引号
string[] names = { "abCDefG", "HIJKlmnOP", "QRsTuvW", "XyZ" };
//ProStToUpper(names);
//ProStrToLower(names);
// ProStrSYH(names);

ProStr(names, delegate(string name)
{
return "\"" + name + "\"";
});
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}


public static void ProStr(string[] name, DelProStr del)
{
for (int i = 0; i < name.Length; i++)
{
name[i] = del(name[i]);
}
}

//public static string StrToUpper(string name)
//{
// return name.ToUpper();
//}

//public static string StrToLower(string name)
//{
// return name.ToLower();
//}

//public static string StrSYH(string name)
//{
// return "\"" + name + "\"";
//}


//public static void ProStToUpper(string[] name)
//{
// for (int i = 0; i < name.Length; i++)
// {
// name[i] = name[i].ToUpper();
// }
//}
//public static void ProStrToLower(string[] name)
//{
// for (int i = 0; i < name.Length; i++)
// {
// name[i] = name[i].ToLower();
// }
//}
//public static void ProStrSYH(string[] names)
//{
// for (int i = 0; i < names.Length; i++)
// {
// names[i] = "\"" + names[i] + "\"";
// }
//}


}
复制代码

 

二、委托的概念:

      把一个方法当作参数传递给另一个方法去执行。

     

复制代码
//声明一个委托指向一个函数
public delegate void DelSayHi(string name);
class Program
{
static void Main(string[] args)
{
//DelSayHi del = SayHiEnglish;//new DelSayHi(SayHiEnglish);
//del("张三");
//Console.ReadKey();
//Test("张三", SayHiChinese);
//Test("李四", SayHiEnglish);
//Console.ReadKey();
}
public static void Test(string name,DelSayHi del)
{
del(name); //调用
}
public static void SayHiChinese(string name)
{
Console.WriteLine("吃了么?" + name);
}
public static void SayHiEnglish(string name)
{
Console.WriteLine("Nice to meet you" + name);
}
}
View Code
复制代码

 

posted @   realyrare  阅读(242)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示