开发者

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:

  1. Positional: What was always supported
  2. 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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜