问题描述
假设我有两个重载版本的 C# 方法:
Say I have two overloaded versions of a C# method:
void Method( TypeA a ) { }
void Method( TypeB b ) { }
我调用该方法:
Method( null );
调用了哪个方法的重载?我该怎么做才能确保调用特定的重载?
Which overload of the method is called? What can I do to ensure that a particular overload is called?
推荐答案
取决于TypeA
和TypeB
.
- 如果其中一个适用(例如,没有从
null
到TypeB
的转换,因为它是一个值类型,但TypeA
是一个引用类型),然后将调用适用的类型. - 否则取决于
TypeA
和TypeB
之间的关系.- 如果存在从
TypeA
到TypeB
的隐式转换,但没有从TypeB
到TypeA
的隐式转换,则将使用使用TypeA
的重载. - 如果存在从
TypeB
到TypeA
的隐式转换,但没有从TypeA
到TypeB
的隐式转换,则将使用使用TypeB
的重载. - 否则,调用是不明确的,将无法编译.
- If exactly one of them is applicable (e.g. there is no conversion from
null
toTypeB
because it's a value type butTypeA
is a reference type) then the call will be made to the applicable one. - Otherwise it depends on the relationship between
TypeA
andTypeB
.- If there is an implicit conversion from
TypeA
toTypeB
but no implicit conversion fromTypeB
toTypeA
then the overload usingTypeA
will be used. - If there is an implicit conversion from
TypeB
toTypeA
but no implicit conversion fromTypeA
toTypeB
then the overload usingTypeB
will be used. - Otherwise, the call is ambiguous and will fail to compile.
有关详细规则,请参阅 C# 3.0 规范的第 7.4.3.4 节.
See section 7.4.3.4 of the C# 3.0 spec for the detailed rules.
这是一个没有歧义的例子.这里
TypeB
派生自TypeA
,这意味着从TypeB
到TypeA
的隐式转换,但反之则不然.因此使用了使用TypeB
的重载:Here's an example of it not being ambiguous. Here
TypeB
derives fromTypeA
, which means there's an implicit conversion fromTypeB
toTypeA
, but not vice versa. Thus the overload usingTypeB
is used:using System; class TypeA {} class TypeB : TypeA {} class Program { static void Foo(TypeA x) { Console.WriteLine("Foo(TypeA)"); } static void Foo(TypeB x) { Console.WriteLine("Foo(TypeB)"); } static void Main() { Foo(null); // Prints Foo(TypeB) } }
一般来说,即使面对其他不明确的调用,为了确保使用特定的重载,只需强制转换:
In general, even in the face of an otherwise-ambiguous call, to ensure that a particular overload is used, just cast:
Foo((TypeA) null);
或
Foo((TypeB) null);
请注意,如果这涉及声明类中的继承(即一个类正在重载由其基类声明的方法),您将陷入另一个问题,您需要转换方法的目标而不是参数.
Note that if this involves inheritance in the declaring classes (i.e. one class is overloading a method declared by its base class) you're into a whole other problem, and you need to cast the target of the method rather than the argument.
这篇关于C#:将 null 传递给重载方法 - 调用哪个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除! - If there is an implicit conversion from
- 如果存在从