假设我有这两个重载函数。
public static void Main(string[]args)
{
int x=3;
fn(x);
}
static void fn(double x)
{
Console.WriteLine("Double");
}
static void fn(float x)
{
Console.WriteLine("Float");
}
为什么编译器会选择float函数?
最佳答案
它遵循 C# 4 规范第 7.5.3.2 节的规则。
int
可隐式转换为 float
和 double
,因此两种候选方法都适用。但是,根据部分,从 int
到 float
的转换“优于”从 int
到 double
的转换7.5.3.2-7.5.3.5:
Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:
- An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists
- ... [irrelevant in this case]
这里,有一个从float
到double
的隐式转换,但是没有从double
到float
的隐式转换- 所以 float
是比 double
更好的转换目标。
关于c# - 方法重载。它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735114/