的Guid ==空不应由编译器被允许编译器、应由、Guid

2023-09-04 00:04:48 作者:Sandm ° 旧梦颜

可能重复:    C#还好有比较值类型为null

  

下面描述的行为是特定于.NET的3.5只

您好,

我对面的最令人惊讶的行为跑在C#编译器;

我有以下的code:

 的Guid G1 = Guid.Empty;
布尔B1 =(G1 == NULL);
 

嗯, GUID是不为空的,因此它永远不可能等于null 。 在比较我正在做的第2行的总是返回false

我进PE转化分区表为类型为GUID之后就成这样了,打开Disk看不到分区就是一个空盘,但是打开我的

如果你做同样的事情为整数时,编译器会发出警告说,结果将永远是错误的:

  INT X = 0;
布尔B2 =(X == NULL);
 

我的问题是:?为什么编译器可以让你比较一个GUID为null 据我所知,它已经知道结果始终是假的。 是内置的转换在这样一种方式,编译器假定空做是可能的值问题 我缺少什么吗?

感谢

解决方案

标记是正确的。定义自己的相等运算符值类型自动得到解除对空的定义,以及为免费版本。可空等于运算符,它有两个可为空的GUID适用于这种情况,将被调用,并且将始终返回false。

在C#2,这个产生的警告,但由于某些原因,该停止生产的GUID到零点的警告,但继续产生一个警告INT到零。我不知道为什么;我还没来得及尚未进行调查。

我的错误表示歉意;我可能重写在C#3。可空逻辑时,除了EX pression树木的语言majorly改变了为空的算术运算的实现顺序搞砸了的预警检测code路径之一;我频频失误四处移动的code。这是一些复杂的code。

Possible Duplicate: C# okay with comparing value types to null

The behaviour described below is specific to .net-3.5 only

Hello,

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

I have the following code:

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

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

If you make the same thing for an integer, the compiler issues an warning saying the result will always be false:

int x=0;
bool b2= (x==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?

Thanks

解决方案

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.

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.

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.

 
精彩推荐
图片推荐