How to resolve ambiguity when argument is null?

2019-02-16 07:43发布

Compiling the following code will return The call is ambiguous between the following methods or properties error. How to resolve it since I can't explicitly convert null to any of those classes?

static void Main(string[] args)
{
    Func(null);
}

void Func(Class1 a)
{

}

void Func(Class2 b)
{

}

7条回答
Bombasti
2楼-- · 2019-02-16 07:47

You could also use a variable:

Class1 x = null;
Func(x);
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-16 07:49
Func((Class1)null);
查看更多
Rolldiameter
4楼-- · 2019-02-16 07:51

The Func() methods accept a reference type as a parameter, which can be null. Since you're calling the method with an explicit null value, the compiler doesn't know whether your null is supposed to be in reference to a Class1 object or a Class2 object.

You have two options:

Cast the null to either the Class1 or Class2 type, as in Func((Class1)null) or Func((Class2)null)

Provide a new overload of the Func() method that accepts no parameters, and call that overload when you don't have an explicit object reference:

void Func()
{
    // call this when no object is available
}
查看更多
唯我独甜
5楼-- · 2019-02-16 07:56

Just an alternative solution I prefer

static void Main(string[] args)
{
    Func(Class1.NULL);
}

void Func(Class1 a)
{ }

void Func(Class2 b)
{ }

class Class1
{
    public static readonly Class1 NULL = null;
}

class Class2
{
    public static readonly Class2 NULL = null;
}
查看更多
男人必须洒脱
6楼-- · 2019-02-16 08:01

Cast null to the type:

Func((Class1)null);
查看更多
闹够了就滚
7楼-- · 2019-02-16 08:01

You should be able to cast null to either of those, the same as you would a variable Func((Class1)null).

查看更多
登录 后发表回答