我有一些类似以下的方法:
static public int GetInt(int _default = 0)
{
// do work, return _default if error
}
static public int? GetInt(int? _default = null)
{
// do work, return _default if error
}
我希望在使用这些方法作为覆盖时,也可以根据我使用它们分配的变量来选择该方法:
int value1 = GetInt();
int? value2 = GetInt();
然而,这会导致“不明确的调用”错误。
我该怎么做才能避免这种情况?
最佳答案
问题是返回类型不是 signature 的一部分C# 中的一个方法。所以你必须以不同的方式命名这些方法。另外,请勿在参数名称中使用下划线。
引用 MSDN 关于方法签名如何工作的内容:
The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
这是一个解决问题的方法。当您返回类型的默认值时,您可以将其设为通用并使用 default(T)
。
static void Main(string[] args)
{
int value1 = GetInt<int>();
int? value2 = GetInt<int?>();
}
static public T GetInt<T>(T defaultValue = default(T))
{
bool error = true;
if (error)
{
return defaultValue;
}
else
{
//yadayada
return something else;
}
}
关于c# - 如何避免使用涉及可空类型的默认参数的重写方法产生不明确的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7195634/