c# 匿名函数作为参数

c# anonymus functions as aparameters

我目前正在使用 C# 并希望使用匿名函数与字段(二维数组)进行交互。我想要实现的目标应该看起来像这样。

//...somewhere in class
private int[][] field1;

interactWithElements(field1, {
  x++;
  //...more complex stuff
});

private void interactWithElements(int[][] field, 
                                  Func anonymusFunction(int x)) {
  for (int x = 0; x < field.Length; x++) {
    for (int y = 0; y < field[0].Length; y++)) {
      anonymusFunction(field[x][y]);
    }
  }
}

在 C# 中可以实现这样的功能吗?什么时候,我该怎么做? 也许与代表一起?

谢谢你。

你快到了:

//...somewhere in class
private int[][] field1;

interactWithElements(field1, x => {
  x++;
  //...more complex stuff
});

您在上面定义的是一个 lamda 表达式 x => { x++; },请参阅此 guide 了解相关信息。

剩下的只需要正确的参数就可以了

private void interactWithElements(
    int[][] field, 
    Action<int> anonymusFunction) 
{
  for (int x = 0; x < field.Length; x++) {
    for (int y = 0; y < field[0].Length; y++)) { // <- you may have meant x instead of 0
      anonymusFunction(field[x][y]);
    }
  }
}

如果你想定义一些内联函数 returns 你可以看看 Func<T, TResult>

如果您对不退货感到满意,请使用 Action<T>

附带说明一下,您可以使用这些委托指定相当多的输入参数,但太多会让人感到困惑!