开发者

How to avoid ambiguous references with overridden methods with default parameters involving nullable types?

I have some methods like the following:

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
}

I was hoping when using these methods as o开发者_如何学Cverrides that the method would be chosen also based on the variable I am using them to assign to:

int value1 = GetInt();
int? value2 = GetInt();

However this results in an "Ambiguous Invocation" error.

What can I do to avoid this?


The problem is that the return type is not part the signature of a method in C#. So you have to name the methods differently. Also, don't use underscore in parameter names.

To quote MSDN on how method signatures work:

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.

This is a way to resolve it. As you return the default of the type, you can just make it generic and use 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;
        }
    }


Switch architecture.

 static public T GetInt<T>(T defaultValue = default(T))
    where T: struct
 {
     // Do Work.

     // On failure
     return defaultValue; 
 }

Then, when you call the function, you should benefit from the generic type:

 int value1 = GetInt(0);
 int? value2 = GetInt(default(int?));

Or if you want to omit the default value:

 int value1 = GetInt<int>();
 int? value2 = GetInt<int?>();

Alternatively, if you just want the default value, you can simply return

 return default(T);

UPDATE: Added constraint - obviously, the problem with making it generic is then you can supply any type; however, your problem then becomes making it compliant to turn an integer into T.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜