C#-Lambda

using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using UnityEngine;

public class TestLambda : MonoBehaviour
{
    /*
        Lambda 的一般规则如下:
        Lambda 包含的参数数量必须与委托类型包含的参数数量相同。
        Lambda 中的每个输入参数必须都能够隐式转换为其对应的委托参数。
        Lambda 的返回值(如果有)必须能够隐式转换为委托的返回类型。
    */

    /*
        下列规则适用于 lambda 表达式中的变量范围:
        捕获的变量将不会被作为垃圾回收,直至引用变量的委托符合垃圾回收的条件。
        在外部方法中看不到 lambda 表达式内引入的变量。
        Lambda 表达式无法从封闭方法中直接捕获 in、ref 或 out 参数。
        Lambda 表达式中的返回语句不会导致封闭方法返回。
        如果跳转语句的目标在块外部,则 lambda 表达式不能包含位于 lambda 函数内部的 goto 语句、 break 语句或 continue 语句。 同样,如果目标在块内部,则在 lambda 函数块外部使用跳转语句也是错误的。
     */

    delegate T delOneArgs<T>(T t);
    delegate W delTwoArgs<T, V, W>(T t, V v);

	// Use this for initialization
	void Start () {
        delOneArgs<int> myDelegate = new delOneArgs<int>(x => x * x);

        int result = myDelegate(5);
        Debug.Log("result = " + result.ToString());

        delOneArgs<string> strDel = new delOneArgs<string>(x => x + x);
        string strResult = strDel("hello");
        Debug.Log("strResult = " + strResult);

        //
        float j = 0.0f;
        delOneArgs<double> doubleDel = x => { j = 5.55f; return x + j; };
        double dResult = doubleDel(1.25);
        Debug.Log("dResult = " + dResult);

        System.Action<double> func = (x) => { if (x == j) Debug.Log("x == j"); else Debug.Log("x != j"); };
        func(5.05f);

        Expression<delOneArgs<int>> exDel = x => x - x;

        //使用空括号指定零个输入参数
        TestAction(() => LambdaType());
	}

    private void TestAction(System.Action action)
    {
        action();
    }

    private void TestAction<T>(System.Action<T> action, T p)
    {
        action(p);
    }
	
    private void LambdaType()
    {
        //隐式类型
        delTwoArgs<int, int, bool> boolDel = new delTwoArgs<int, int, bool>((x, y) => x == y);
        Debug.Log(boolDel(5, 5));
        Debug.Log(boolDel(5, 4));

        //输入参数类型必须全部为显式或全部为隐式
        //显示类型
        delTwoArgs<int, string, bool> boolDel2 = new delTwoArgs<int, string, bool>((int x, string s) => s.Length >= x);
        Debug.Log(boolDel2(5, "hello"));
    }

	// Update is called once per frame
	void Update () {
		
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值