我看到这个问题,想知道为什么在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?
“Nothing”和“null”是不同的,它们在处理相同情况时采用了不同的方式,这是否意味着两种语言之间存在差异?
为什么或者说哪些方面的处理不同,导致了一种语言中可以使用这个值,而另一种语言中却不能?
【更新】
鉴于一些评论,我进一步尝试了一下……似乎在VB.NET中,如果你想允许某些东西为空,你实际上必须使用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'
太奇怪了...