我在一段代码中看到了这一点,想知道是否有人可以帮助我澄清这一点。
public string MethodName(string str, int? x = null)
{
if(x != null)
{
....
}
}
第二个函数参数是我感到困惑的地方:
int? x = null
我知道 Nullable 类型,但我对这里的语法感到困惑,我以前从未见过。为什么输入参数中有一个“= null”?我阅读它的方式是将 x 设置为 null,如果 x 始终为 null,它永远不会首先命中它。
最佳答案
这里的方法签名 x
是一个 optional parameter ,这意味着如果您不想更改参数的默认值,则可以省略此参数。
考虑以下对该函数的调用。
调用 1:有两个参数
MethodName("AValue",10); // str = AValue and x=10
调用 2:跳过可选参数
MethodName("AValue"); // str = AValue and x=null
注意:-
To define an optional parameter you should assign a default value to that parameter, so that if it is not specified in the function call the default value will be taken.
关于c# - 可空类型作为 C# 中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37848905/