可以在c#数组中存储lambda表达式吗?

本文关键字:lambda 表达式 存储 数组 | 更新日期: 2023-09-27 18:01:42

我正在编写一个游戏AI引擎,我想在数组中存储一些lambda表达式/委托(多个参数列表)。

像这样:

 _events.Add( (delegate() { Debug.Log("OHAI!"); }) );
 _events.Add( (delegate() { DoSomethingFancy(this, 2, "dsad"); }) );

在c#中是可能的吗?

可以在c#数组中存储lambda表达式吗?

您可以制作一个List<Action>:

List<Action> _events = new List<Action>();
_events.Add( () => Debug.Log("OHAI!")); //for only a single statement
_events.Add( () =>
    {
        DoSomethingFancy(this, 2, "dsad");
        //other statements
    });

然后调用单个项目:

_events[0]();

你可以使用System.Action.

var myactions = new List<Action>();
myactions .Add(new Action(() => { Console.WriteLine("Action 1"); }) 
myactions .Add(new Action(() => { Console.WriteLine("Action 2"); }) 
foreach (var action in myactions)
  action();