检查嵌套 类 中的空(无)变量的整洁方法
Tidy way to check for Null (Nothing) Variables in nested classes
如果 Boolean
值 FormFoo.Bar.Baz.Quux
存在且为 True
,我想采取一些措施。但是,Bar
和 Baz
是 class 类型的成员,可能是 Nothing
(在这种情况下,不应执行操作)。
我目前有以下代码,但它很丑陋:
If (Not FormFoo.Bar Is Nothing) AndAlso (Not FormFoo.Bar.Baz Is Nothing) AndAlso FormFoo.Bar.Baz.Quux Then
DoSomething()
End If
是否有其他可读性更强的方法来执行此测试?
如果您使用的是 Visual Studio 2015,您可以使用 Null-Propagating operator 来执行此操作:
If FormFoo.Bar?.Baz?.Quux Then
' If branch taken only if Bar and Baz are non-null AND Quux is True
DoSomething()
End If
或者我想你可以检查 NullReferenceExceptions
但这有点混乱,我不鼓励在正常代码操作中抛出异常:
Try
If FormFoo.Bar.Baz.Quux Then
DoSomething()
End If
Catch ex As NullReferenceException
'ignore null reference exceptions
End Try
除此之外,您可以将代码重构为一个单独的函数,这甚至可能使其更具可读性:
If DoINeedToDoSomething() Then
DoSomething()
End If
Private Function DoINeedToDoSomething() As Boolean
'return false is any object is null/nothing
If FormFoo.Bar Is Nothing OrElse FormFoo.Bar.Baz Is Nothing Then Return False
'object are not null so return the value of the boolean
Return FormFoo.Bar.Baz.Quux
End Function
请注意,您的原始代码可以通过使用 IsNot
稍微整理一下 - 这是 Microsoft 推荐的标准:
If (FormFoo.Bar IsNot Nothing) AndAlso (FormFoo.Bar.Baz IsNot Nothing) AndAlso FormFoo.Bar.Baz.Quux Then
DoSomething()
End If
如果 Boolean
值 FormFoo.Bar.Baz.Quux
存在且为 True
,我想采取一些措施。但是,Bar
和 Baz
是 class 类型的成员,可能是 Nothing
(在这种情况下,不应执行操作)。
我目前有以下代码,但它很丑陋:
If (Not FormFoo.Bar Is Nothing) AndAlso (Not FormFoo.Bar.Baz Is Nothing) AndAlso FormFoo.Bar.Baz.Quux Then
DoSomething()
End If
是否有其他可读性更强的方法来执行此测试?
如果您使用的是 Visual Studio 2015,您可以使用 Null-Propagating operator 来执行此操作:
If FormFoo.Bar?.Baz?.Quux Then
' If branch taken only if Bar and Baz are non-null AND Quux is True
DoSomething()
End If
或者我想你可以检查 NullReferenceExceptions
但这有点混乱,我不鼓励在正常代码操作中抛出异常:
Try
If FormFoo.Bar.Baz.Quux Then
DoSomething()
End If
Catch ex As NullReferenceException
'ignore null reference exceptions
End Try
除此之外,您可以将代码重构为一个单独的函数,这甚至可能使其更具可读性:
If DoINeedToDoSomething() Then
DoSomething()
End If
Private Function DoINeedToDoSomething() As Boolean
'return false is any object is null/nothing
If FormFoo.Bar Is Nothing OrElse FormFoo.Bar.Baz Is Nothing Then Return False
'object are not null so return the value of the boolean
Return FormFoo.Bar.Baz.Quux
End Function
请注意,您的原始代码可以通过使用 IsNot
稍微整理一下 - 这是 Microsoft 推荐的标准:
If (FormFoo.Bar IsNot Nothing) AndAlso (FormFoo.Bar.Baz IsNot Nothing) AndAlso FormFoo.Bar.Baz.Quux Then
DoSomething()
End If