为什么在这种情况下可空类型不相等? [英] Why nullable types will not be equal in this case?
问题描述
令人惊讶的是,下面的代码不会成功.
Surprisingly the code bellow will not succeed.
int? n1 = null;
int? n2 = null;
Assert.IsTrue(n1 <= n2); // Fails here
你知道为什么吗?
推荐答案
在 C#(和 VB.Net)中使用可空值的布尔逻辑常常违反逻辑.我发现理解它的最好方法是记住null 不是一个值".因为 null 不是一个值,所以您不能对其进行任何操作.因此,诸如1 > null
"和1
Using boolean logic with null nullable values in C# (and VB.Net) often times defies logic. I find the best way to make sense of it is to remember that "null is not a value". Because null is not a value you cannot do any operations on it. Hence things like "1 > null
" and "1 < null
" are both true.
这里是详细指南:http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
如果您确实想将 null 视为一个值,那么您可以使用 GetValueOrDefaultMethod() 将 null 等同于默认值.例如
If you do want to treat null as a value then you could use the GetValueOrDefaultMethod() to equate null with the default value. For example
Assert.IsTrue(n1.GetValueOrDefault() <= n2.GetValueOrDefault()); // True
这有点冗长,但它会完成工作.
This is a bit verbose but it will get the job done.
这篇关于为什么在这种情况下可空类型不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!