简体   繁体   English

c# 方法重载选择错误的重载并编译

[英]c# method overload picks the wrong overload and compiles

I have the following:我有以下内容:

EnErrorCodes WriteToCard(EnRegs address, byte data)
EnErrorCodes WriteToCard(EnRegs address, ushort data)
EnErrorCodes WriteToCard(EnRegs address, uint data)
EnErrorCodes WriteToCard(EnRegs address, float data)
EnErrorCodes WriteToCard(EnRegs address, double data)

but had missed the ulong overload.但错过了ulong超载。

When then using the overloads blindly with a ulong , the compiler picked the float overload rather than throwing an error.然后,当盲目地使用ulong重载时,编译器选择了float重载而不是抛出错误。

Took ages to work out why the system wasn't writing that data properly, only ctrl+clicking on the WriteToCard method where it was called then took it to the float overload.花了很长时间才弄清楚为什么系统没有正确写入该数据,只有 ctrl+单击调用它的WriteToCard方法,然后将其带到浮点重载。

Creating the ulong one obviously sorted it but I don't understand why it happened as it was a rather annoying feature to try and find.创建ulong显然对它进行了排序,但我不明白它为什么会发生,因为它是一个相当烦人的尝试和查找功能。

This is because of Implicit numeric conversion .这是因为Implicit数字转换

在此处输入图像描述

If you look at highlighted part of above image, C# converts ulong to float , double , decimal .如果您查看上图中突出显示的部分,C# 会将ulong转换为floatdoubledecimal

As you have WriteToCard() with float parameter, if you pass data with ulong as a type, compiler implictly converts it to float and execute it, instead of throwing an error.由于您有带有float参数的WriteToCard() ,如果您使用ulong作为类型传递data ,编译器会将其隐式转换为 float 并执行它,而不是引发错误。

ulong can be implicitly converted to float and double , so there are two valid candidates for selecting method overload . ulong可以隐式转换floatdouble ,因此选择方法重载有两个有效的候选者。 The float one is selected because it is better conversion target :选择float是因为它是更好的转换目标

Given two different types T1 and T2, T1 is a better conversion target than T2 if no implicit conversion from T2 to T1 exists, and at least one of the following holds:给定两种不同的类型 T1 和 T2,如果不存在从 T2 到 T1 的隐式转换,则 T1 是比 T2 更好的转换目标,并且至少满足以下一项:

  • An implicit conversion from T1 to T2 exists存在从 T1 到 T2 的隐式转换
  • ... ...

So there is no implicit conversion from double to float , but there is one from float to double所以没有从doublefloat的隐式转换,但是有一个从floatdouble

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM