简体   繁体   中英

Shared/Static Variable Should Be Nothing but Isn't - what gives?

I have the following code:

Public Class TestClass
    Public Sub Main()
        If theGlobal IsNot Nothing Then Throw New Exception("What gives!")
    End Sub

    Private Shared theGlobal As Object = Nothing
    Private Shared ReadOnly Property Global
        Get
            If theGlobal Is Nothing Then
                theGlobal = New Object()
            End If

            Return theGlobal 
        End Get
    End Property
End Class

Am stumped... Why is theGlobal object NOT Nothing?

Assuming that's really your code, my guess is that you're running this in the debugger with a breakpoint, and the watch window is evaluating the property, which is initializing theGlobal .

Just a guess, based on what I've seen before in similar situations.

If that doesn't help, try to write a short but complete console application which reproduces the problem, and which we can all run.

I think you meant

If Global Is Nothing Then Throw New Exception("What gives!")

You have to access the Global property for the field to be initialized, according to your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM