示例:
public int foo(int x, int optionalY = 1, int optionalZ = 2) { ... }
我希望这样调用:
int returnVal = foo(5,,8);
换句话说,我想提供x
和z
,但我想对Y
使用默认值,即optionalY = 1。
然而,Visual Studio不喜欢,,
,请帮忙。示例:
public int foo(int x, int optionalY = 1, int optionalZ = 2) { ... }
我希望这样调用:
int returnVal = foo(5,,8);
换句话说,我想提供x
和z
,但我想对Y
使用默认值,即optionalY = 1。
然而,Visual Studio不喜欢,,
,请帮忙。int returnVal = foo(5, optionalZ: 8);
这被称为命名参数。许多其他语言都提供了此功能,它们通常使用 foo(5, optionalZ=8)
语法,当查看其他语言的代码时了解这种语法很有用。
另一种动态提供参数的方法是在类中实现您的方法,并向类构造函数提供命名参数。为什么不像这里提到的那样在同一行代码上添加对方法的调用呢:C#如何定义命名参数。
var p = new PersonInfo { Name = "Peter", Age = 15 }.BuildPerson();
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; }
这个模式等同于我们如何使用智能技术浏览函数的变化。
optionalX
应该改成optionalY
。 - moinudin