C#: Passing null to overloaded method - which method is called?(C#:将 null 传递给重载方法 - 调用哪个方法?)
问题描述
假设我有两个重载版本的 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 传递给重载方法 - 调用哪个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
- If there is an implicit conversion from
- 如果存在从
本文标题为:C#:将 null 传递给重载方法 - 调用哪个方法?
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
