c# - 方法重载。它是如何工作的?

标签 c# overloading

假设我有这两个重载函数。

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 可隐式转换为 floatdouble,因此两种候选方法都适用。但是,根据部分,从 intfloat 的转换“优于”从 intdouble 的转换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]

这里,有一个从floatdouble的隐式转换,但是没有从doublefloat的隐式转换- 所以 float 是比 double 更好的转换目标。

关于c# - 方法重载。它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735114/

相关文章:

c++ - C++ 标准中的重载与默认参数

c# - 在 VB6 中使 .NET 控件透明

c++ - 重载 >> 运算符,在 while 循环中填充 vector

c# - 禁用文本框显示其中键入的旧数据的能力

c# - 从 Windows 服务打印

c++ - 如何在不需要对其他文件进行多次更改的情况下处理派生类的多个重载

operator-overloading - 如何在 Julia 中重载/重新定义二元运算符?

delphi重载程序

java - WebElements 列表中的 Selenium Web Driver Stale Reference 异常

c# - 如何将mysql表中的数据添加到C#表单中