Optional Specification of some C# Optional Parameters
Suppose you ha开发者_开发百科ve 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
? It would look something like...
SomeMethod(_, false);
... which would translate to...
SometMethod(false, false);
... at compile-time. Is this possible?
Take a look at named parameters.
SomeMethod(bar: false);
With C#4 you can specify parameters to functions in 2 ways:
- Positional: What was always supported
- Named: You can specify the name of each parameter and put them in any order
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);
}
精彩评论