In VB.NET http://en.wikipedia.org/wiki/Visual_Basic_.NET有时候是这样的:
Dim x As System.Nullable(Of Decimal) = Nothing
Dim y As System.Nullable(Of Decimal) = Nothing
y = 5
If x <> y Then
Console.WriteLine("true")
Else
Console.WriteLine("false") '' <-- I got this. Why?
End If
但在 C# 中会发生这种情况:
decimal? x = default(decimal?);
decimal? y = default(decimal?);
y = 5;
if (x != y)
{
Debug.WriteLine("true"); // <-- I got this -- I'm with you, C# :)
}
else
{
Debug.WriteLine("false");
}
为什么会有差异?
VB.NET 和 C#.NET 是不同的语言,由不同的团队构建,他们对使用做出了不同的假设;在本例中是 NULL 比较的语义。
我个人更喜欢 VB.NET 语义,它本质上为 NULL 提供了“我还不知道”的语义。然后将5与“我还不知道”进行比较。自然是“我还不知道”;即NULL。这具有在(大多数(如果不是全部))SQL 数据库中镜像 NULL 行为的额外优点。这也是对三值逻辑的更标准(比 C# 的)解释,如下所示here http://en.wikipedia.org/wiki/Three-valued_logic.
C# 团队对 NULL 的含义做出了不同的假设,从而导致了您所显示的行为差异。Eric Lippert 写了一篇关于 C# 中 NULL 含义的博客 http://blogs.msdn.com/b/ericlippert/archive/2012/03/26/null-is-not-false.aspx。 Per Eric Lippert:“我还写了有关 VB / VBScript 和 JScript 中 null 语义的文章here http://blogs.msdn.com/b/ericlippert/archive/2003/09/30/53120.aspx and here http://blogs.msdn.com/b/ericlippert/archive/2003/10/01/53128.aspx".
在任何可能存在 NULL 值的环境中,重要的是要认识到不再可以依赖排除中间定律(即 A 或 ~AN 同义反复为真)。
Update:
A bool
(as opposed to a bool?
) can only take the values TRUE and FALSE. However a language implementation of NULL must decide on how NULL propagates through expressions. In VB the expressions 5=null
and 5<>null
BOTH return false. In C#, of the comparable expressions 5==null
and 5!=null
only the second first [updated 2014-03-02 - PG] returns false. However, in ANY environment that supports null, it is incumbent on the programmer to know the truth tables and null-propagation used by that language.
Update
Eric Lippert 关于语义的博客文章(在下面的评论中提到)现在位于:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)