[英]Optional Specification of some C# Optional Parameters
Suppose you have a method with the following signature: 假设您有一个带有以下签名的方法:
public void SomeMethod(bool foo = false, bool bar = true) { /* ... */ }
When calling this method, is there a way to specify a value for bar
and not foo
? 调用此方法时,有没有办法为bar
而不是foo
指定值? It would look something like... 它看起来像......
SomeMethod(_, false);
... which would translate to... ......这会转化为......
SometMethod(false, false);
... at compile-time. ......在编译时。 Is this possible? 这可能吗?
看一下命名参数。
SomeMethod(bar: false);
With C#4 you can specify parameters to functions in 2 ways: 使用C#4,您可以通过两种方式为函数指定参数:
With positional parameters there is no way to specify only the 2nd default parameter. 使用位置参数,无法仅指定第二个默认参数。 With named parameters there is. 有了命名参数。 Simply omit the first named parameter. 只需省略第一个命名参数即可。
Here is an example: 这是一个例子:
static void test(bool f1 = false, bool f2 = false)
{
//f1 == false and f2 == true
}
static void Main(string[] args)
{
test(f2: true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.