gpt4 book ai didi

c# - 可空类型如何使用比较运算符处理空值?

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

有没有人知道 C# 如何处理与 Nullable<T> 的比较的具体信息?当比较的一侧为空时类型?

据我对编译器的实验了解,比较似乎总是返回 false,但我找不到任何文档来支持这一点。这是该语言的一个真正特性(因此我可以指望它),还是一个可能在未来版本中改变的实现细节?

换句话说,下面的方法返回true是否暗示y.HasValue ,你能给我指出一些证明它确实如此的文档吗?

    public bool foo(int x, int? y)
{
return x < y;
}

最佳答案

Does anyone have concrete information on how C# handles comparisons with Nullable types when one side of the comparison is null?

是 - C# 语言规范,第 7.3.7 节。在这种情况下,它是一个关系运算符:

For the relation operators < > <= >= a lifted form of an operator exists if the operand types are both non-nullable types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

其他运算符也有类似的详细部分。

当对语言的某些方面如何工作有疑问时(以及它是有保证的还是特定于实现的),C# 语言规范应该是您的第一站。

关于c# - 可空类型如何使用比较运算符处理空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507463/

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