gpt4 book ai didi

c# - 为什么我可以将 sbyte 与所有其他数字类型*except* ulong 进行比较?

转载 作者:IT王子 更新时间:2023-10-29 04:22:02 27 4
gpt4 key购买 nike

您可以在 sbyte 和 byte、int、uint、short、ushort、long、double 和 float 之间进行 >、<、== 等比较。但不是乌龙。

我的大脑在爆炸。谁能解释为什么 sbyte 可以与 uint 相比,但不是 ulong?

public bool sbyte_ulong_compare(sbyte x, ulong y)
{
return x < y; // compiler error CS0019
}

此外,使用 unchecked 不会让事情变得更好。大脑融化。

另一个编辑。这有效:

public bool sbyte_ulong_compare(sbyte x, ulong y)
{
//
// returns x < y
//
if (x < 0)
return true;

if (y > 127)
return true;

return ((long)x < (long)y);
}

最佳答案

dthorpe 和 Jon 的答案很接近但不太正确。

正确的推理如下。

规范指出:

For an operation of the form x op y, where op is a comparison operator, overload resolution is applied to select a specific operator implementation.

好的,重载解析必须使用哪些运算符实现?它们是:

bool operator <(int x, int y);
bool operator <(uint x, uint y);
bool operator <(long x, long y);
bool operator <(ulong x, ulong y);
bool operator <(float x, float y);
bool operator <(double x, double y);
bool operator <(decimal x, decimal y);

加上所有枚举类型的枚举小于运算符,加上上述每个类型的提升为可空版本。

过载解决方案必须首先消除不适用 运算符,然后从剩余的一组适用运算符中确定最佳 运算符。

int、uint、long 和 enum 运算符(及其提升形式)都被删除,因为 ulong 不会隐式转换为这些类型。

uint 和 ulong 运算符(及其提升形式)都被删除了,因为 sbyte 不会隐式转换为这些类型。

剩下的

bool operator <(float x, float y);
bool operator <(double x, double y);
bool operator <(decimal x, decimal y);

以及它们的提升形式。我们现在必须从这六个中确定最佳运算符。

我们所说的“最佳”是什么意思?比较两个运算符时,具有更具体 操作数类型的运算符更好。 “更具体”是指“Tiger”比“Animal”更具体,因为所有 Tigers 都可以转换为 Animal,但并非所有 Animals 都可以转换为 Tiger。

很明显,未提升的形式优于所有相应的提升形式。不可为 null 的类型比其对应的可为 null 的类型更具体,因为不可为 null 的类型始终可转换为其可为 null 的类型,但反之则不然。我们可以消除提升的形式。

还剩下三个。这三个哪个最好?

float 比 double 更具体。每个 float 都可以转换为 double,但不是每个 double 都可以转换为 float。因此消除了双重。剩下两个。

bool operator <(float x, float y);
bool operator <(decimal x, decimal y);

哪一个是最好的?没有从 float 到十进制的隐式转换。没有从十进制到 float 的隐式转换。因此两者都不比另一个好。

因此无法确定最佳运算符。重载解析失败。

我们决定报告一个通用的错误消息,简单地说没有这样的运算符可以做你想做的事,而不是给出看似奇怪和令人困惑的错误消息“运算符重载解析失败,因为 float 既不比 float 好也不坏十进制”。我认为这是一个合理的设计选择。

关于c# - 为什么我可以将 sbyte 与所有其他数字类型*except* ulong 进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4327679/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com