C# lambda 表达式和 var 关键字

lambda 表达式 (int x, int y) => { return x + y }

delegate 所引用的函数可以用匿名的方式定义
和 js 一样,lambda 表达式会捕捉定义时上下文中的变量,形成闭包。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class learn_lambda
    {
        delegate int Two(int a, int b);
        static Two m = null;
        static void Main()
        {
            m = new Two((int a, int b) => {
                return a + b;
            });
            Console.WriteLine(m(1, 2)); // 3
            int c = 1;
            m = new Two((int a, int b) =>
            {
                return a + b + c;
            });
            Console.WriteLine(m(1, 2)); // 4
            c = 2; // modify the value at &c
            Console.WriteLine(m(1, 2)); // 5, proving that 'c' is calculated at runtime
            Run2();                     // 4
            m = GetTwo();
            Console.WriteLine(m(1, 2)); // 6
            Console.ReadKey();
        }

        static void Run2()
        {
            int c = 2; // 毫无影响
            Console.WriteLine(m(1, 2));
        }

        static Two GetTwo()
        {
            int c = 3;
            return new Two((int a, int b) =>
            {
                return a + b + c; // c still exists even the stack for GetTwo is gone
            });
        }
    }
}

lambda 表达式还可以这样写

(int a, int b) => a + b

例如

m = (int a, int b) => a + b; // making it more compact

var

var 有点像 C艹 里的 auto ,声明变量时可以用 var 作为替代具体的类型,编译器会推断具体类型。
var 的确定时刻是编译时。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{

    class learn_var
    {
        class Shit
        {
            string component;
            public Shit(string str)
            {
                this.component = str;
            }
        }
        static void Main()
        {
            var a = 1;
            var b = 1.0;
            var shit = new Shit("nothing");
            Console.WriteLine(a.GetType());
            Console.WriteLine(b.GetType());
            Console.WriteLine(shit.GetType());
            Console.ReadKey();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值