C# “匿名函数”知识点,代码记录

今天学习委托时,偶然接触到了匿名函数,感觉挺新奇的,就把代码记录下来,以后有机会全面学习时再拿出来看看!


匿名函数是一个函数的简写,它没有函数名称。

我们把一个函数赋值给委托时,就可以使用匿名函数

下面是简单例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 匿名函数 {

    // 定义委托
    public delegate void DelSayHi(string name);

    class Program {
        static void Main(string[] args) {

            // 匿名函数 (函数的类型是什么取决于委托的定义)
            DelSayHi del = delegate (string name) {
                Console.WriteLine("你好!" + name);
            };  // 这里需要写下分号 ;

            del("张三");


            del = delegate (string name) {
                Console.WriteLine("hello" + name);
            };

            del("李四");

            Console.ReadKey();
        }
    }
}

代码中,我们定义了一个void返回值,有一个string类型参数的委托;
然后我们定义委托时就是用到了匿名函数,将匿名函数赋值给该委托。

匿名函数有没有返回值类型取决于委托有没有。

最后直接通过委托调用函数。

运行截图:
在这里插入图片描述


再写一个例子

获取数组的最大值

代码:

/*匿名函数小例子*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 泛型 {

    // 定义委托,实现两数相减
    public delegate int Delegate(object o1, object o2);


    class Program {
        static void Main(string[] args) {
            object[] arry1 = { 1, 2, 3, 5, 4, 6, 9, 8 };
            object[] arry2 = { "asdfasdlg", "xzvcnryt", "waerw4thbvzxt", "asdfgh" };


            // 匿名函数
            object result = GetMax(arry1, delegate (object o1, object o2) {
                return (int)o1 - (int)o2;
            });
            Console.WriteLine("最大值:" + result);


            // 匿名函数
            object result2 = GetMax(arry2, delegate (object o1, object o2) {
                return o1.ToString().Length - o2.ToString().Length;
            });
            Console.WriteLine("最大值:" + result2);

            Console.ReadKey();
        }

        // 获取数组的最大值
        public static object GetMax(object[] arr, Delegate del) {
            object max = arr[0];

            for (int i = 0; i < arr.Length; i++) {

                // 委托实现max减去arr[i],当小于0,说明max比它小
                if (del(max, arr[i]) < 0) {
                    max = arr[i];
                }
            }

            return max;
        }

    }
}

运行截图:
在这里插入图片描述


总结
注意看匿名函数的定义,知道该怎么定义匿名函数就行了,具体他是用在哪方面,我也不知道,我猜测应该是用在一个函数只调用一次时,就使用匿名函数的方式取调用他吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpp_learners

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值