C#vs VB.NET – 处理null结构

我碰到了这个,并想知道是否有人可以解释为什么这在VB.NET中工作时我会期望它会失败,就像在C#中一样

//The C# Version struct Person { public string name; } ... Person someone = null; //Nope! Can't do that!! Person? someoneElse = null; //No problem, just like expected 

但是在VB.NET中……

 Structure Person Public name As String End Structure ... Dim someone As Person = Nothing 'Wha? this is okay? 

没有什么不同于null( Nothing!= null – LOL?) ,或者这只是处理两种语言之间相同情况的不同方式?

为什么或两者之间的处理方式不同,这使得一个可以在一个,而不是另一个?

[更新]

鉴于一些评论,我对此进行了更多的讨论……如果你想在VB.NET中允许某些东西为null,那么好像你真的必须使用Nullable …例如…

 'This is false - It is still a person' Dim someone As Person = Nothing Dim isSomeoneNull As Boolean = someone.Equals(Nothing) 'false' 'This is true - the result is actually nullable now' Dim someoneElse As Nullable(Of Person) = Nothing Dim isSomeoneElseNull As Boolean = someoneElse.Equals(Nothing) 'true' 

太奇怪了……

如果我没记错的话,VB中的’Nothing’意味着“默认值”。 对于值类型,对于引用类型,这是null的默认值。 因此,不给结构赋予任何东西,完全没有问题。

Nothing大致相当于相关类型的default(T) 。 (刚检查过,对于字符串也是如此 – 即在字符串的上下文中Nothing是空引用。)

我试图在MSDN上搜索它,但在VB端找不到任何相关的东西。 当在C#上搜索“struct”时,它清楚地返回它是一个值类型并且不能被指定为null,因为……它是一个值。

但是,在查看VB.NET关键字“结构”时,它并没有说“值类型”。 相反,它说

Structure语句定义可以自定义的复合值类型。

所以……对象?

那是我的猜测。 我想引用这种行为,但找不到任何。

此外,结构是值类型(很像int,char等),因此是不可为空的。

因为一个Structure可能由几个不同的类型组成(不是单个值Type,而是几种不同类型的可能组合),因此询问它是否为“Nothing”会破坏使用“Nothing”的逻辑。 根据您正在测试的类型,没有什么可以进行不同的测试,因此复杂的类型不符合使用“Nothing”的逻辑。 然而,对于这种类型的测试,即,具有其所有组件成员处于其各自“Nothing”值的结构,我们使用函数“IsNothing”。 例如:

 Public Class Employees Public Structure EmployeeInfoType Dim Name As String ' String Dim Age as Integer ' Integer Dim Salary as Single ' Single End Structure Private MyEmp as New EmployeeInfoType Public Function IsEmployeeNothing(Employee As EmployeeInfoType) As Boolean If **IsNothing**(Employee) Then Return True Else Return False End If End Function End Class