编译器不应允许 Guid == null [英] Guid == null should not be allowed by the compiler

查看:25
本文介绍了编译器不应允许 Guid == null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The behaviour described below is specific to .net-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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆