我遇到了这个,并想知道是否有人可以解释为什么这在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
在字符串的上下文中是空引用.)