简体   繁体   English

C# 函数和可选参数

[英]C# functions and optional parameters

I know that in C# it is possible to define optional parameters.我知道在 C# 中可以定义可选参数。 My question is directed at how flexible this is.我的问题是针对这有多灵活。

Let f be a function as below, with a mandatory and b , c optional:设 f 为 a function,如下所示, a 为必填项, bc可选:

class Test {
   public void f(int a, int b = 2, int c = 3) {
      //...
   }
}

Now, I know I can call the function in the following ways:现在,我知道我可以通过以下方式拨打 function:

f(1) -> a equals 1, b equals 2, c equals 3 f(1) -> a 等于 1,b 等于 2,c 等于 3

f(11,22) -> a equals 11, b equals 22, c equals 3 f(11,22) -> a 等于 11,b 等于 22,c 等于 3

f(11,22,33) -> a equals 11, b equals 22, c equals 33 f(11,22,33) -> a 等于 11,b 等于 22,c 等于 33

How do I do to not specify b , but a and c ?我该怎么做才能不指定b ,而是指定ac

Try: 尝试:

f(11, c: 33)

And take a look at the documentation 并查看文档

您可以在参数前添加参数名称:

f(1, c:3);

Using named arguments : 使用命名参数

f(a: 5, c: 6);

Although, strictly speaking in my example, you don't have to qualify the a: 虽然,严格来说,在我的例子中,你没有资格a:

f(5, c: 6);

Another possibility would be to define the method with other parameters and call the original one with them using this syntax:另一种可能性是用其他参数定义方法,并使用以下语法用它们调用原始方法:

public void f(int a, int c = 3) => f(a, 2, c)

More comfortable usability if you call it, but gets fiddly to define if you have more than 2 optional parameters.如果您调用它,则使用起来会更舒适,但如果您有两个以上的可选参数,则定义起来会很麻烦。

您使用命名参数:

f( a:100, c:300);

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

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