检查VB.NET中的Null值

时间:2014-11-18 23:28:19

标签: vb.net variables visual-studio-2012 null nullreferenceexception

我有一个搜索AD属性(extensionAttribute3)的函数。如果属性有值,它可以正常工作,但是如果没有设置它,则会出现“对象引用未设置为对象实例”的错误。这总是出错:

CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString

我尝试使用“If IsNothing”和“IsNot Nothing”来检查dirResult&上的NULL值。 CurrentPIN,但它仍然是错误的。如何成功检查NULL值?

检查dirResult是否为NULL:

Private Function GetUserProperties()
    Dim ADName As String = GetLogonName()
    Dim CurrentPIN As String = Nothing
    Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
    Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
    dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
    dirSearcher.PropertiesToLoad.Add("extensionAttribute3")
    dirSearcher.SearchScope = SearchScope.Subtree
    Dim dirResult As SearchResult = dirSearcher.FindOne()
    If IsNothing(dirResult) Then
        Return "<not set>"
    Else
        CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
        Return CurrentPIN
    End If
End Function

检查CurrentPIN是否为NULL:

   Private Function GetUserProperties()
        Dim ADName As String = GetLogonName()
        Dim CurrentPIN As String = Nothing
        Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
        Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
        dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute3")
        dirSearcher.SearchScope = SearchScope.Subtree
        Dim dirResult As SearchResult = dirSearcher.FindOne()
        CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
        If IsNothing(CurrentPIN) Then
            Return False
        Else
            Return CurrentPIN
        End If
    End Function

1 个答案:

答案 0 :(得分:1)

您应该在属性中检查NULL(&#34; extensionAttribute3&#34;):

If dirResult Is Nothing OrElse dirResult.GetDirectoryEntry.Properties("extensionAttribute3") Is Nothing Then
    Return "<not set>"
Else
    CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
    Return CurrentPIN
End If

说明:

Is Nothing是IMO检查NULL的一种更简洁的方法,而AFAIK也可以为您节省堆栈级别。

如果extensionAttribute3没有值,则表示您有异常,因为

CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString

被翻译为

CurrentPIN = <NULL>.Value.ToString

在dirResult上检查NULL只是为了防止将来可能出现异常。