c# - 可空类型作为 C# 中的函数参数

标签 c#

我在一段代码中看到了这一点,想知道是否有人可以帮助我澄清这一点。

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/

相关文章:

c# - DRY CLR 表值函数

c# - c# 事件是串行处理还是并行处理?

c# - 如何选择轻版本数据库系统

c# - 并行 ForEach 在生成之前等待 500 毫秒

c# - 从 SQL Server 存储过程返回多个值

c# - Windows Phone 8.1 (WinRT) : Custom Looping Selector

c# - 如何 "clear"一个对象?

c# - 在 ControlTemplate 中,我想将相同的样式应用于所有 TextBlock

c# - 使用属性路由在 Controller 中获取操作的 url

c# - 如何以排序安全的方式绑定(bind)到 DataGridRow 的 IsSelected 属性?