23

我遇到了这个问题,想知道是否有人可以解释为什么它在 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 ( Nothing != null - LOL?)是否不同,或者这只是两种语言之间处理相同情况的不同方式?

为什么或两者之间的处理方式有所不同,这使得这在一个中可以解决,而在另一个中则不行?

[更新]

鉴于一些评论,我对此更加混乱......似乎如果你想在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'

太诡异了……

4

5 回答 5

30

如果我没记错的话,VB 中的“Nothing”表示“默认值”。对于值类型,这是默认值,对于引用类型,这将是 null。因此,没有为结构分配任何内容根本没有问题。

于 2008-11-19T21:55:10.650 回答
12

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

于 2008-11-19T21:57:46.480 回答
1

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

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

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

所以……对象?

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

于 2008-11-19T22:01:19.170 回答
0

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

于 2008-11-19T22:00:23.150 回答
-1

因为一个结构可能由几种不同的类型组成(不是单个值类型,而是几种不同类型的可能组合),所以询问它是否为“无”会破坏使用“无”的逻辑。没有任何测试会根据您正在测试的类型而有所不同,因此复杂类型不符合使用“无”的逻辑。然而,对于这种类型的测试,即结构的所有组件成员都处于各自的“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
于 2013-06-29T04:03:18.573 回答