C# Lambda简单理解
Lambda一般用于定义回调函数,把回调函数放在参数当中,等合适的时候再使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class LambdaStudy : MonoBehaviour
{
// Use this for initialization
void Start()
{
TestOne(value => {
Debug.Log("正在运行TestOne");
});
}
public void TestOne(Action<int> callback)
{
Debug.Log("TestOne开始运行");
TestTwo(value =>
{
Debug.Log("正在运行TestTwo");
value++;
callback(value);
Debug.Log("TestOne运行完毕,此时value为:" + value);
});
}
public void TestTwo(Action<int> callback)
{
Debug.Log("TestTwo开始运行");
TestThree(value =>
{
Debug.Log("正在运行TestThree");
value++;
callback(value);
Debug.Log("TestTwo运行完毕,此时value为:" + value);
});
}
public void TestThree(Action<int> callback)
{
Debug.Log("TestThree开始运行");
int value = 10;
callback(value);
Debug.Log("TestThree运行完毕,此时value为:" + value);
}
}
结果如下:

通俗来讲,把Lambda和事务结合起来使用就是: “ method(member => expression)”
先运行method,等method中需要回调时再去运行member=>expression。

本文通过具体的Unity脚本示例介绍了如何使用C#中的Lambda表达式作为回调函数,并逐步展示了多个方法之间的调用流程及Lambda表达式的实际应用。
1602

被折叠的 条评论
为什么被折叠?



