假设我有两个重载版本的 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 的重载.null to TypeB because it's a value type but TypeA is a reference type) then the call will be made to the applicable one.TypeA and TypeB.
TypeA to TypeB but no implicit conversion from TypeB to TypeA then the overload using TypeA will be used.TypeB to TypeA but no implicit conversion from TypeA to TypeB then the overload using TypeB will be used.有关详细规则,请参阅 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 from TypeA, which means there's an implicit conversion from TypeB to TypeA, but not vice versa. Thus the overload using TypeB 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 传递给重载方法 - 调用哪个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检查字符串是否为空How to check if String is null(如何检查字符串是否为空)
Equals(item, null) 或 item == nullEquals(item, null) or item == null(Equals(item, null) 或 item == null)
覆盖 == 运算符.如何与空值进行比较?Overriding == operator. How to compare to null?(覆盖 == 运算符.如何与空值进行比较?)
成员访问中的问号在 C# 中是什么意思?What does the question mark in member access mean in C#?(成员访问中的问号在 C# 中是什么意思?)
||(或)C# 中的 Linq 运算符The || (or) Operator in Linq with C#(||(或)C# 中的 Linq 运算符)
C# 空合并运算符等效于 C++C# null coalescing operator equivalent for c++(C# 空合并运算符等效于 C++)