我遇到了这个问题,并且想知道是否有人可以解释为什么它在VB.NET中工作时我希望它会失败,就像它在C#中那样#/ p>

//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)。 (刚检查过,对于字符串也是如此 - 即<=>是字符串上下文中的空引用。)

我试图在MSDN上搜索它,但在VB端找不到任何相关内容。搜索<!> quot; struct <!>时;在C#上,它清楚地返回它是一个值类型,并且不能被指定为null,因为......它是一个值。

然而,当查看VB.NET关键字<!> quot; Structure <!> quot;它没有说<!>“;值类型<!>”;相反,它说

  

Structure语句定义了一个   你可以使用复合值类型   定制

所以......对象?

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

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

因为一个Structure可能由几个不同的类型组成(不是单个值Type,而是几种不同类型的可能组合),所以要求它是否为<!>“Nothing <!>”;会打破使用<!>“; Nothing <!>”的逻辑。根据您正在测试的类型,没有任何测试方式不同,因此复杂类型不符合使用<!>“Nothing <!>”的逻辑。然而,对于这种类型的测试,即,具有其所有组件成员在它们各自的“没有”的结构。值,我们使用函数<!> quot; IsNothing <!> quot;。例如:

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top