更新时间:2023-11-30 22:15:34
问题是string
和object
都可以为空,因此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
param1
和param2
具有相同的值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.