编译器不应允许 Guid == null

编程入门 行业动态 更新时间:2024-10-28 12:20:29
本文介绍了编译器不应允许 Guid == null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下描述的行为仅适用于 -3.5

The behaviour described below is specific to -3.5 only

我刚刚遇到了 C# 编译器中最令人惊讶的行为;

I just ran across the most astonishing behavior in the C# compiler;

我有以下代码:

Guid g1 = Guid.Empty; bool b1= (g1 == null);

好吧,Guid 不可为空,因此它永远不可能等于 null.我在第 2 行中进行的比较总是返回 false.

Well, Guid is not nullable therefore it can never be equal to null. The comparison i'm making in line 2 always returns false.

如果你对一个整数做同样的事情,编译器会发出警告说结果总是错误的:

int x=0; bool b2= (x==null);

我的问题是:为什么编译器让您将 Guid 与 null 进行比较?据我所知,它已经知道结果总是错误的.内置转换是否以编译器确实假定 null 是可能值的方式完成?我在这里遗漏了什么吗?

My question is: Why does the compiler lets you compare a Guid to null? According to my knowledge, it already knows the result is always false. Is the built-in conversion done in such a way that the compiler does assume null is a possible value? Am I missing anything here?

推荐答案

Mark 是正确的.定义自己的相等运算符的值类型也会自动免费获得定义为可空的版本.带有两个可空 guid 的可空相等运算符适用于这种情况,将被调用,并且将始终返回 false.

Mark is correct. Value types that define their own equality operators automatically get lifted-to-nullable versions defined as well, for free. The nullable equality operator that takes two nullable guids is applicable in this situation, will be called, and will always return false.

在 C# 2 中,这产生了一个警告,但由于某种原因,这停止为 guid-to-null 产生警告,但继续为 int-to-null 产生警告.我不知道为什么;我还没有时间去调查.

In C# 2, this produced a warning, but for some reason, this stopped producing a warning for guid-to-null but continues to produce a warning for int-to-null. I don't know why; I haven't had time to investigate yet.

我为错误道歉;在 C# 3 中重写可空逻辑时,我可能搞砸了警告检测代码路径之一.在语言中添加表达式树主要改变了可空算术运算的实现顺序;我在移动该代码时犯了很多错误.这是一些复杂的代码.

I apologize for the error; I probably screwed up one of the warning-detection code paths when rewriting the nullable logic in C# 3. The addition of expression trees to the language majorly changed the order in which nullable arithmetic operations are realized; I made numerous mistakes moving that code around. It's some complicated code.

更多推荐

编译器不应允许 Guid == null

本文发布于:2023-06-05 01:14:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/508840.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   不应   null   Guid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!