How to skip optional parameters in C#?

a 夏天 提交于 2019-12-29 05:39:07

问题


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.

Visual Studio does not like the ,,

Please help.


回答1:


If this is C# 4.0, you can use named arguments feature:

foo(x: 5, optionalZ: 8); 

See this blog for more information.




回答2:


In C# 4.0 you can name the arguments occurring after skipped defaults like this:

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.




回答3:


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#

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




回答4:


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.

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.



来源:https://stackoverflow.com/questions/4630444/how-to-skip-optional-parameters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!