重载null歧义 [英] Overloading null ambiguity

查看:69
本文介绍了重载null歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

  void Method(string param1, string param2);
  void Method(string param1, object param2);

当我使用以下方法调用该方法时:

When I call the method using the following:

  method("string", null);

它给我一个错误,因为调用是模棱两可的,编译器不知道要调用哪个版本,因为这两个方法都接受null作为第二个参数.

It gives me an error because the call is ambiguous, the compiler does not know which version to call, because both methods accept null as the second parameter.

如何在不更改其中一个方法名称的情况下克服此问题?第一种方法永远不会有null.

How do I overcome this without changing the method name in one of them? the first method will never have null.

推荐答案

问题是stringobject都可以为空,因此null可以引用该方法的重载.您必须强制转换null值(听起来很愚蠢),以明确地说出您要调用的重载.

The problem is that both string and object are nullable, so null could refer to either overload of the method. You have to cast the null value—as stupid as that sounds—to say explicitely which overload you want to call.

method("string", (string) null);
method("string", (object) null);

这基本上与您定义了任何一种类型的变量并在随后传递该变量时相同:

This is basically the same as if you defined a variable of either type and passed that then:

string param1 = null;
object param2 = null;

method("string", param1); // will call the string overload
method("string", param2); // will call the object overload

param1param2具有相同的值null,但是变量具有不同的类型,这就是为什么编译器能够准确指出需要使用哪个重载.上面带有显式强制转换的解决方案是相同的.它将类型注释为null值,然后用于推断正确的重载-无需声明变量.

Both param1 and param2 have the same value, null, but the variables are of different types which is why the compiler is able to tell exactly which overload it needs to use. The solution above with the explicit cast is just the same; it annotates a type to the null value which is then used to infer the correct overload—just without having to declare a variable.

这篇关于重载null歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆