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 () {
}
}