当 C# 函数参数包含 `= null` 时,这意味着什么?
What does it mean when a C# function parameter contains `= null`?
我正在经历一个 MVC tutorial 并在一个函数的开头看到这行代码:
private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
测试后,我可以看到该函数有效,但我不明白如何 函数参数起作用。 object selectedDepartment = null
是做什么的?
我进行了一般的互联网搜索,但尚未找到答案。
我想我的问题确实有两个方面:
- 参数的
= null
部分有什么作用?
- 是否可以完成但不一定应该完成的事情?
这会将参数设置为默认值(如果未提供)并防止在未提供参数时出现编译时错误。参见:
Setting the default value of a C# Optional Parameter
基本上这个参数现在是可选的,因此您可以通过以下两种方式之一调用该函数:
PopulateDepartmentsDropDownList() //selectedDepartment will be set to null as it is not provided
或
PopulateDepartmentsDropDownList(myObject) //selectedDepartment will become myObject
表示可以调用
PopulateDepartmentsDropDownList()
或
PopulateDepartmentsDropDownList("something")
两者都是因为编译器会将第一个转换为
PopulateDepartmentsDropDownList(null)
此功能称为 Optional Arguments
我建议你阅读this blog post
这意味着该参数将为空,除非您决定传递一些东西。所以换句话说,它是可选的。
可以做到,也没有什么不妥。这是很常见的做法。
= null
是参数的默认值,它的功能等效于
private void PopulateDepartmentsDropDownList()
{
PopulateDepartmentsDropDownList(null);
}
private void PopulateDepartmentsDropDownList(object selectedDepartment)
{
//Your code here.
}
因此,如果您可以调用不带参数的函数 PopulateDepartmentsDropDownList()
,它将调用 1 参数版本并传入 null。
我正在经历一个 MVC tutorial 并在一个函数的开头看到这行代码:
private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
测试后,我可以看到该函数有效,但我不明白如何 函数参数起作用。 object selectedDepartment = null
是做什么的?
我进行了一般的互联网搜索,但尚未找到答案。
我想我的问题确实有两个方面:
- 参数的
= null
部分有什么作用? - 是否可以完成但不一定应该完成的事情?
这会将参数设置为默认值(如果未提供)并防止在未提供参数时出现编译时错误。参见:
Setting the default value of a C# Optional Parameter
基本上这个参数现在是可选的,因此您可以通过以下两种方式之一调用该函数:
PopulateDepartmentsDropDownList() //selectedDepartment will be set to null as it is not provided
或
PopulateDepartmentsDropDownList(myObject) //selectedDepartment will become myObject
表示可以调用
PopulateDepartmentsDropDownList()
或
PopulateDepartmentsDropDownList("something")
两者都是因为编译器会将第一个转换为
PopulateDepartmentsDropDownList(null)
此功能称为 Optional Arguments
我建议你阅读this blog post
这意味着该参数将为空,除非您决定传递一些东西。所以换句话说,它是可选的。
可以做到,也没有什么不妥。这是很常见的做法。
= null
是参数的默认值,它的功能等效于
private void PopulateDepartmentsDropDownList()
{
PopulateDepartmentsDropDownList(null);
}
private void PopulateDepartmentsDropDownList(object selectedDepartment)
{
//Your code here.
}
因此,如果您可以调用不带参数的函数 PopulateDepartmentsDropDownList()
,它将调用 1 参数版本并传入 null。