简体   繁体   English

如何在C#中跳过可选参数?

[英]How to skip optional parameters in C#?

Example: 例:

public int foo(int x, int optionalY = 1, int optionalZ = 2) { ... }

I'd like to call it like this: 我想这样称呼它:

int returnVal = foo(5,,8); 

In other words, I want to provide x and z , but I want to use the default for Y , optionalY = 1. 换句话说,我想提供xz ,但我想使用Y的默认值, optionalY = 1.

Visual Studio does not like the ,, Visual Studio不喜欢,,

Please help. 请帮忙。

If this is C# 4.0, you can use named arguments feature: 如果这是C#4.0,则可以使用命名参数功能:

foo(x: 5, optionalZ: 8); 

See this blog for more information. 有关更多信息,请参阅此博客

In C# 4.0 you can name the arguments occurring after skipped defaults like this: 在C#4.0中,您可以命名在跳过默认值之后发生的参数,如下所示:

int returnVal = foo(5, optionalZ: 8);

This is called as named arguments . 这称为命名参数 Several others languages provide this feature, and it's common form them to use the syntax foo(5, optionalZ=8) instead, which is useful to know when reading code in other languages. 其他几种语言提供了这一功能,并且通常使用语法foo(5, optionalZ=8)代替它,这对于了解何时阅读其他语言的代码很有用。

Another dynamic way to supply parameters of your choise is to implement your method(s) in a class and supply named parameters to the class constructor. 另一种提供选择参数的动态方法是在类中实现方法,并为类构造函数提供命名参数。 Why not even add calls to methods on same line of code as mentioned here : How to define named Parameters C# 为什么不在这里提到的同一行代码上添加对方法的调用: 如何定义命名参数C#

var p = new PersonInfo { Name = "Peter", Age = 15 }.BuildPerson(); var p = new PersonInfo {Name =“Peter”,Age = 15} .BuildPerson();

This is a late answer, but for the people who get into this. 这是一个迟到的答案,但对于那些进入这个问题的人来说。 One could also use Overloads,that uses the same name as the method/function, but with a different set of parameters. 也可以使用Overloads,它使用与方法/函数相同的名称,但使用不同的参数集。

ea EA

int SummAll (int a=0, int b=1, int c=2)
{return a+b+c;}

int SumAll (int a=0;int c=10) //skipping B 
{return a+c; }

This pattern equals how with intellicense we can browse through variations of functions. 这种模式等同于我们可以浏览函数变体的intellicense。

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

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