是否可以将lambda表达式存储在数组C#中

nec*_*ciu 7 .net c# lambda

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

像这样的东西:

 _events.Add( (delegate() { Debug.Log("OHAI!"); }) );
 _events.Add( (delegate() { DoSomethingFancy(this, 2, "dsad"); }) );
Run Code Online (Sandbox Code Playgroud)

在C#中有可能吗?

gun*_*171 7

你可以做一个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
    });
Run Code Online (Sandbox Code Playgroud)

然后调用单个项目:

_events[0]();
Run Code Online (Sandbox Code Playgroud)


mil*_*uak 5

你可以使用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();
Run Code Online (Sandbox Code Playgroud)