为什么会出现在检查空针对VB.NET和C#的值不同?出现在、不同、VB、NET

由网友(苡后啲苡后)分享简介:在 VB.NET 出现这种情况:Dim x As System.Nullable(Of Decimal) = NothingDim y As System.Nullable(Of Decimal) = Nothingy = 5If x y ThenConsole.WriteLine("true")Else...

在 VB.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#中出现这种情况:

But in C# this happens:

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");
}

为什么有区别吗?

Why is there a difference?

推荐答案

VB.NET和C#.NET有不同的语言,通过谁作出不同的假设使用不同的团队建设;在这种情况下的一个NULL比较的语义。

VB.NET and C#.NET are different languages, built by different teams who have made different assumptions about usage; in this case the semantics of a NULL comparison.

我个人的preference是VB.NET的语义,这在本质上给出了NULL的语义我还不知道。随后的5到我还不知道的比较。自然是我还不知道;即NULL。这具有镜像NULL的行为的额外优点(大多数,如果不是全部)SQL数据库。这也是一个比较标准(比C#的)三值逻辑的跨pretation,因为这里解释

My personal preference is for the VB.NET semantics, which in essence gives NULL the semantics "I don't know yet". Then the comparison of 5 to "I don't know yet". is naturally "I don't know yet"; ie NULL. This has the additional advantage of mirroring the behaviour of NULL in (most if not all) SQL databases. This is also a more standard (than C#'s) interpretation of three-valued logic, as explained here.

C#团队由不同的假设是什么NULL表示,导致你表现出的行为差异。 埃里克利珀写了一篇博客有关的NULL在C#中的意义。每埃里克利珀:我也写了一篇关于空的VB / VBScript和JScript的这里和这里。

The C# team made different assumptions about what NULL means, resulting in the behaviour difference you show. Eric Lippert wrote a blog about the meaning of NULL in C#. Per Eric Lippert: "I also wrote about the semantics of nulls in VB / VBScript and JScript here and here".

在其中NULL值是可能的任何环境中,imprtant认识到排中的法(即A或〜A是tautologically真)不再可以依靠。

In any environment in which NULL values are possible, it is imprtant to recognize that the Law of the Excluded Middle (ie that A or ~A is tautologically true) no longer can be relied on.

更新:

A 布尔(而不是一个布尔?)只能走值为TRUE和FALSE。然而,一个语言实现的NULL必须决定如何NULL传播通过EX pressions。在VB中的前pressions 5 = NULL 5℃;&GT;空都返回假的。在C#中,可比EX pressions 5 == NULL 5!= NULL 只有第二首的 [更新2014年3月2日 - PG] 的返回false。然而,在支持null任何环境,这是义不容辞的责任程序员知道使用该语言的真值表和零传播。

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.

阅读全文

相关推荐

最新文章