问题描述
假设我有两个重载版本的 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
nulltoTypeBbecause it's a value type butTypeAis a reference type) then the call will be made to the applicable one. - Otherwise it depends on the relationship between
TypeAandTypeB.- If there is an implicit conversion from
TypeAtoTypeBbut no implicit conversion fromTypeBtoTypeAthen the overload usingTypeAwill be used. - If there is an implicit conversion from
TypeBtoTypeAbut no implicit conversion fromTypeAtoTypeBthen the overload usingTypeBwill 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
TypeBderives fromTypeA, which means there's an implicit conversion fromTypeBtoTypeA, but not vice versa. Thus the overload usingTypeBis 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 传递给重载方法 - 调用哪个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End
- If there is an implicit conversion from
- 如果存在从


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)