2018-07-26 【c#】匿名函数

定义:一段函数或表达式,直接嵌套在程序里面,没有名称;和c#中的委托有密切的联系;
委托:相当于把函数传递到程序里;匿名:把没有名称的函数传递到程序里

1.三种写法的区分:普通函数delegate获取 | 匿名函数delegate获取 | Lambda表达式函数delegate获取

using System;
using System.Collections.Generic;
using System.Text;

namespace Anonymous
{
    class Program
    {
        delegate void TestDelegate(string s);

        static void MethodTest(string s)
        {
            Console.WriteLine(s);
        }

        static void Main(string[] args)
        {
            TestDelegate tdA = new TestDelegate(MethodTest);

            //c# 2.0  匿名方法
            TestDelegate tdB = delegate (string s) { Console.WriteLine(s); };

            //c# 3.0  Lambda写法
            TestDelegate tdC = (x) => { Console.WriteLine(x); };

        }
    }
}

2.泛型代理的应用
现在知道了可以这么用,但是还不知道什么时候这么用。待日后再说。
目前还是觉得直接调用一个方法比较方便。我干嘛要获得这个函数引用(delegate),然后通过这种方式调用函数?可能这种lambda和匿名函数中用到代理的地方比较多。看上去写起来较为方便简洁?

add:
看了Enumerable.Where 方法,就是跟这玩意一样一样的。
delegate 返回值泛型 方法名<定义用到的泛型1,定义用到的泛型2 .... >(传入参数泛型)

using System;
using System.Collections.Generic;
using System.Text;

namespace Anonymous
{
    delegate int del(int i);
    delegate TResult Func<TArg0, TResult>(TArg0 arg0);

    class Program
    {

        static void Main(string[] args)
        {
            Lambda();

            Console.ReadLine();
        }

        private static void StartThread()
        {
            System.Threading.Thread t1 = new System.Threading.Thread
                (delegate ()
                {
                    Console.WriteLine("Hi! ");
                    Console.WriteLine("Here comes Wenxuejia!");
                });
            t1.Start();
        }

        private static void Lambda()
        {
            del myDelegate = (x) => { return x * x; };
            Console.WriteLine(myDelegate(5));


            Func<int, bool> myFunc = x => x == 5;
            Console.WriteLine(myFunc(4));
            Console.WriteLine(myFunc(5));

        }

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,410评论 19 139
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,140评论 8 265
  • 前言 人生苦多,快来 Kotlin ,快速学习Kotlin! 什么是Kotlin? Kotlin 是种静态类型编程...
    任半生嚣狂阅读 26,631评论 9 118
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,573评论 1 32
  • 自己在说别人的时候头头是道,但是在说自己的时候却无言以对。错误总是在不经意间出现,自己在做选择的时候却有时间限制,...
    沙克诺莎娃阅读 260评论 0 0

友情链接更多精彩内容