如何可空类型与比较运算符处理空值?运算符、类型、何可

2023-09-03 12:08:35 作者:Milkshake 奶昔

有没有人对如何C#处理与可空&LT比较具体的资料; T> 类型时比较一边是空

当我从与编译器尝试理解,好像是比较总是返回假的,但我无法找到任何文件做后盾的时候了。这是语言的真实要素(因此是我可以指望),或者这是一个实现细节,可能在未来的版本的变化?

在换句话说,做了下面的方法返回true意味着 y.HasValue ,你可以点我的一些文件,证明它呢?

 公共BOOL富(INT X,INT?Y)
    {
        返回X< ÿ;
    }
 

解决方案   

有没有人对如何C#处理的比较可空类型的具体信息,在比较的一侧是空?

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

  SQL中的where条件查询 比较运算符 逻辑运算符 模糊查询 范围查询 空判断

有关关系运算符< > < => = 操作的提升形式存在,如果操作数的类型都为非可空类型,如果结果类型为布尔 。该提升形式是通过将一个修改为每个操作数类型构造的。提升运算符产生的值如果一个或两个操作数都为空。否则,提升运营商进行解包操作数和应用基础运算符以产生布尔的结果。

有其他运营商类似的细节部分。

当有疑问如何在语言的某些方面的作品(不论它保证或实施专用),C#语言规范应该是调用您的第一个端口。

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

As I understand from experimenting with the compiler, it seems that the comparison always returns false, but I can't find any documentation to back that up. Is this a real feature of the language (and thus something I can count on), or is this an implementation detail that might change in future versions?

In other words, does the following method returning true imply y.HasValue, and can you point me to some documentation that proves that it does?

    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?

Yes - the C# language specification, section 7.3.7. In this case, it's a relational operator:

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.

There are similarly detailed sections for other operators.

When in doubt about how some aspect of the language works (and whether it's guaranteed or implementation-specific), the C# language specification should be your first port of call.