模糊的方法调用

时间:2013-09-23 17:30:13

标签: c# ambiguity

我有以下代码

class Program
{
    static void Main()
    {
        A a = new A();
        a.M(null);
    }
}

class A
{
    public void M(int? i)
    { }

    public void M(string s)
    { }
}

我有一个错误,因为电话不明确。我需要更改M方法的调用,而不向Main方法添加任何行并访问类A以使其变得正确。有人可以告诉我怎么做吗?

3 个答案:

答案 0 :(得分:3)

您可以使用显式强制转换:

A a = new A();
a.M((string)null);

a.M((int?)null);

帮助编译器选择正确的重载。请注意,C#编译器无法根据null字面值确定要调用的方法重载。

有关高级主题,请考虑Eric的文章What is the type of the null literal?

修改

由于您的参数名称不同,您可以使用命名参数,这些参数可用,因为 C#4.0

a.M(i : null);

a.M(s : null);

答案 1 :(得分:2)

您可以使用演员表,default keywordint?new int?()(由于how Nullable types work,也与null相同})。您还可以使用named parameters来消除歧义。或者,当然,如果您可以添加另一行,则可以在变量中声明您的值并将其传入。

// these call the int? overload
a.M(default(int?));
a.M((int?)null);
a.M(new int?());
a.M(i: null);
int? i = null;
a.M(i);

// these call the string overload
a.M(default(string));
a.M((string)null);
a.M(s: null);
string s = null;
a.M(s);

答案 2 :(得分:0)

答案是,如果您无法改变现有的呼叫站点,则不能以这种方式重载成员M.

据推测,您正在添加两种方法中的一种,并且可以更改呼叫站点以调用新方法。更改要使用的新呼叫站点的方法名称。