当参数为空时如何解决歧义?
编译以下代码将返回 The call is ambigacy Between the followingmethods orproperties
错误。由于我无法显式地将 null
转换为任何这些类,如何解决这个问题?
static void Main(string[] args)
{
Func(null);
}
void Func(Class1 a)
{
}
void Func(Class2 b)
{
}
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)
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您还可以使用变量:
You could also use a variable:
将
null
转换为类型:Cast
null
to the type:使用
as
进行转换使其在具有相同功能的情况下稍微更具可读性。Using
as
for the casting makes it slightly more readable with the same functionality.Func()
方法接受引用类型作为参数,该参数可以为 null。由于您使用显式null
值调用该方法,因此编译器不知道您的 null 是否应该引用Class1
对象或Class2
对象。您有两个选择:
将 null 转换为
Class1
或Class2
类型,如Func((Class1)null)
或Func((Class2)null)
提供不接受参数的
Func()
方法的新重载,并在没有显式对象引用时调用该重载:The
Func()
methods accept a reference type as a parameter, which can be null. Since you're calling the method with an explicitnull
value, the compiler doesn't know whether your null is supposed to be in reference to aClass1
object or aClass2
object.You have two options:
Cast the null to either the
Class1
orClass2
type, as inFunc((Class1)null)
orFunc((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:您应该能够将 null 转换为其中任何一个,就像变量
Func((Class1)null)
一样。You should be able to cast null to either of those, the same as you would a variable
Func((Class1)null)
.只是我更喜欢的替代解决方案
Just an alternative solution I prefer