[C#基础]Lambda表达式

今天在看别人的代码时发现了这个——“=>”,看起来像c语言中的指针,又像是这个表情——":)",不管像什么,确实把我难倒了,于是决定学习一下。


简单地说,Lambda表达式就像是匿名委托。

using UnityEngine;
using System.Collections;

//若要创建 Lambda 表达式,需要在 Lambda 运算符 => 左侧指定输入参数(如果有),
//然后在另一侧输入表达式或语句块。

//仅当 lambda 只有一个输入参数时,括号才是可选的;否则括号是必需的。
//括号内的两个或更多输入参数使用逗号加以分隔

public class TestCSharp : MonoBehaviour{

    delegate void TestDelegate();
    delegate void TestDelegate2(string s);
    delegate void TestDelegate3(string m,string n);
    delegate int TestDelegate4(int i);

	// Use this for initialization
	void Start () 
    {
        //=> 右侧是语句块,可以包含任意数量的语句
        TestDelegate testDelA = () => { print("开始测试!"); print("准备好了吗?"); };
        TestDelegate2 testDelB = (x) => { print(x); };
        TestDelegate3 testDelC = (x,y) => { print(x + y); };
        testDelA();
        testDelB("HelloWorld");
        testDelC("世界","你好");

        //=> 右侧是表达式
        TestDelegate4 testDelD = x => x * 11;
        int j = testDelD(8); //j = 88
        print(j);

        //=> 右侧是方法
        TestDelegate testDelE = () => TestA();
        testDelE();


        TestDelegate testDelF = () => TestB();
        testDelF += () => TestC();
        testDelF();

        TestD(() => TestB(), () => TestC());
	}

    void TestA()
    {
        print("再见了!");
    }

    void TestB()
    {
        print("啊!");
    }

    void TestC()
    {
        print("我又回来了!");
    }

    void TestD(TestDelegate a,TestDelegate b)
    {
        a();
        b();
    } 
}


运行结果:


在TestD方法中,Lambda表达式直接当参数传给了一个委托,你懂的。。

还有就是msdn上讲解的也挺详细的,点这里传送。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值