以 null 作为参数的重载函数
Overload function with null as argument
我有一个接收字符串作为参数的函数:
public async Task<List<string>> GetNames(string name)
{
...
}
我想将该函数重载为如下内容:
public async Task<List<string>> GetNames(string name = null)
{
...
}
但在那种情况下,我收到以下错误:
"Type 'Nameservice' already defines a member called 'GetNames' with the same types".
当参数为 null 时,如何正确重载此方法以供使用。
How can I overload this method properly to be used when argument is null.
重载旨在提供一个名称相同但参数集不同的方法。它并不意味着对参数的值做出断言。如果你想这样做,你需要在方法内部进行,在这种情况下调用另一个方法
public async Task<List<string>> GetNames(string name)
{
if(name is null)
{
return await GetNames();
}
else
{
// use "name"
}
}
public async Task<List<string>> GetNames()
{
// do something different
}
澄清:
GetNames(string name = null)
这不是重载,因为参数集保持不变。这使得参数可选!这样调用站点就不再需要它了。
我有一个接收字符串作为参数的函数:
public async Task<List<string>> GetNames(string name)
{
...
}
我想将该函数重载为如下内容:
public async Task<List<string>> GetNames(string name = null)
{
...
}
但在那种情况下,我收到以下错误:
"Type 'Nameservice' already defines a member called 'GetNames' with the same types".
当参数为 null 时,如何正确重载此方法以供使用。
How can I overload this method properly to be used when argument is null.
重载旨在提供一个名称相同但参数集不同的方法。它并不意味着对参数的值做出断言。如果你想这样做,你需要在方法内部进行,在这种情况下调用另一个方法
public async Task<List<string>> GetNames(string name)
{
if(name is null)
{
return await GetNames();
}
else
{
// use "name"
}
}
public async Task<List<string>> GetNames()
{
// do something different
}
澄清:
GetNames(string name = null)
这不是重载,因为参数集保持不变。这使得参数可选!这样调用站点就不再需要它了。