简体   繁体   English

在 C# 中“按名称”传递的参数

[英]Arguments passed "by name" in C#

The Scala programming language has a neat feature, called pass by name arguments , that allows some arguments to only be evaluated if required. Scala编程语言有一个简洁的特性,称为pass by name arguments ,它允许某些参数仅在需要时才被评估。

For example, it's possible to write a while loop using a curried method such as the following:例如,可以使用以下柯里化方法编写while循环:

// This is Scala code. A simulated while loop
@scala.annotation.tailrec
def myWhile(condition: => Boolean)(actions: => Unit): Unit = {
  if(condition) {
    actions
    myWhile(condition)(actions)
  }
}

This method can be used like a regular while loop, thanks to Scala 's syntactic sugar, closures and—of particular interest here—the ability to pass expressions as function arguments, which are evaluated when referenced (as indicated by the : => type argument declaration).这个方法可以像常规的while循环一样使用,这要归功于Scala的语法糖、闭包和——这里特别感兴趣的——将表达式作为函数参数传递的能力,当被引用时会被评估(如: => type所示参数声明)。

For example, the following prints "Hello!"例如,以下打印“Hello!” to the console ten times:到控制台十次:

var i = 0
myWhile(i < 10) {
  println("Hello!")
  i += 1
}

For those who need to understand what is happening, the expression i < 10 is evaluated each time condition appears inside the if(...) statement inside the method, similarly, println("Hello!"); i += 1对于那些需要了解正在发生的事情的人,每次condition出现在方法内的if(...)语句中时,都会评估表达式i < 10 ,类似地, println("Hello!"); i += 1 println("Hello!"); i += 1 is evaluated each time actions appears in the body of the method.每次actions出现在方法的主体中时,都会评估println("Hello!"); i += 1 When recursively calling myWhile for the next iteration, the expressions are passed as is, since the method requires expressions, not values.当为下一次迭代递归调用myWhile时,表达式按原样传递,因为该方法需要表达式,而不是值。 Scala terms these pass by name arguments. Scala术语这些通过名称参数传递。

If these arguments were passed by value instead, then i < 10 would be passed to myWhile as false , while "Hello!"如果这些参数是按值传递的,那么i < 10将作为false传递给myWhile ,而 "Hello!" would be printed exactly once, i would be incremented once, and the loop would execute infinitely.将只打印一次, i将增加一次,并且循环将无限执行。

( Scala is primarily a functional language, and this code is not even close to being FP , but it's a simple example.) Scala主要是一种函数式语言,这段代码甚至不接近FP ,但它是一个简单的例子。)

My question is, is there a way to pass arguments in this way to a C# function?我的问题是,有没有办法以这种方式将参数传递给C#函数? Also note that I'm restricted to using C# 7.3 .另请注意,我仅限于使用C# 7.3 :-( :-(

It sounds like you can get somewhat close withFunc`1 and Action :听起来您可以使用Func`1Action获得一些接近:

void MyWhile(Func<bool> condition, Action action) {
  while (condition()) {
    action();
  }
}

and calling as:并调用:

int i = 0;
MyWhile(() => i < 10, () => {
  Console.WriteLine("Hello!");
  ++i;
});

The syntax is a bit different, but the idea is similar.语法有点不同,但想法是相似的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM