如果参数为null,如何解决歧义?

编译以下代码将返回The call is ambiguous between the following methods or properties错误The call is ambiguous between the following methods or properties 。 如何解决它因为我无法将null显式转换为任何这些类?

 static void Main(string[] args) { Func(null); } void Func(Class1 a) { } void Func(Class2 b) { } 

 Func((Class1)null); 

null转换为类型:

 Func((Class1)null); 

您还可以使用变量:

 Class1 x = null; Func(x); 

使用as铸件使其具有相同的function稍微更具可读性。

 Func(null as Class1); 

Func()方法接受引用类型作为参数,该参数可以为null。 由于您使用显式null值调用方法,因此编译器不知道您的null是应该引用Class1对象还是Class2对象。

你有两个选择:

将null转换为Class1Class2类型,如Func((Class1)null)Func((Class2)null)

提供不接受任何参数的Func()方法的新重载,并在没有显式对象引用时调用该重载:

 void Func() { // call this when no object is available } 

您应该能够将null转换为其中任何一个,与变量Func((Class1)null)

只是我喜欢的替代解决方案

 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; } 
Interesting Posts