c# - 如何避免使用涉及可空类型的默认参数的重写方法产生不明确的引用?

标签 c# nullable default-parameters

我有一些类似以下的方法:

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/

相关文章:

c# - ODataProperties (System.Web.OData.Extensions - OData v4) 缺少 '' 模型属性

c# - GUI 线程上的 IDbConnection.BeginTransaction,使用异步/等待,导致多次调用死锁

mysql - Laravel 迁移值从 null 到 string

.net - 可选参数 : "empty" vs "not provided"

c# - 如何用空格连接 session 值

c# - PHP $_GET ['something' ] 在 C# 中等效

c# - .NET 1.1 使用具有可空类型的 Web 服务,该怎么办?

c# - DNN C# 模块开发 - 可为空值

python - Python 中默认参数的范围

python - "Least Astonishment"和可变默认参数