【问题标题】:c# anonymus functions as aparametersc#匿名函数作为参数
【发布时间】:2017-04-04 15:23:33
【问题描述】:

我目前从 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# 中可以实现这样的事情吗?当它是时,我该怎么做? 也许和代表一起?

谢谢你。

【问题讨论】:

  • 我认为你的循环有一个小错误,你的意思可能是field[x].Length而不是field[0].Length
  • 对我的代码没有任何影响,该字段始终是一个完美的矩形,否则其他代码可能会遇到问题;)
  • 很酷:)

标签: c# parameters delegates anonymous-function


【解决方案1】:

你快到了:

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

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

您在那里定义的是一个 lamda 表达式 x =&gt; { 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]);
    }
  }
}

如果你想定义一些返回值的内联函数,请查看Func&lt;T, TResult&gt;

如果您很高兴不返回任何东西,请使用Action&lt;T&gt;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 2011-05-11
    • 2012-09-10
    相关资源
    最近更新 更多