在asp.net中正确定义单例

时间:2009-10-14 11:11:32

标签: asp.net-2.0

我有以下类是单例实现:

Imports Microsoft.VisualBasic
Imports System.Xml


Public Class GlobalController

    Private Shared instance As GlobalController
    Private ControlsXmlDoc As XmlDocument
    Private xmldocpath As String

    Sub New()
        ControlsXmlDoc = New XmlDocument
        xmldocpath = HttpContext.Current.Server.MapPath("~/cp/GlobalControl.xml")
        ControlsXmlDoc.Load(xmldocpath)
    End Sub

    Shared Function GetInstance() As GlobalController
        If instance Is Nothing Then
            Return New GlobalController
        Else
            Return instance
        End If
    End Function

    Shared Property IsExtracting() As Boolean
        Get
            Return Boolean.Parse(GetInstance.ControlsXmlDoc.SelectNodes("global/extraction/proceed").Item(0).InnerText)
        End Get
        Set(ByVal value As Boolean)
            HttpContext.Current.Application.Lock()
            Dim node As XmlNode = GetInstance.ControlsXmlDoc.SelectNodes("global/extraction/proceed").Item(0)
            If Not Boolean.Parse(node.InnerText) = value Then
                node.InnerText = value.ToString
                node.Normalize()
                SaveDocument()
                GetInstance.ControlsXmlDoc.Load(GetInstance.xmldocpath)
            End If
            HttpContext.Current.Application.UnLock()
        End Set
    End Property

    Shared Sub SaveDocument()
        GetInstance.ControlsXmlDoc.Save(GetInstance.xmldocpath)
    End Sub

End Class

在我的页面中,我正在做这样的事情:

GlobalController.IsExtracting = False
Response.Write(GlobalController.IsExtracting)

我总是把输出视为“真实”。代码有什么问题?

2 个答案:

答案 0 :(得分:1)

根据此链接Operator precedence and associativity!(或vb.net Not)的优先级高于==(VB.NET中的=);所以,你的表达式总是被评估为

Not(True) And False

并且永远不会输入If声明。

尝试使用Boolean.Parse(node.InnerText) != valueNot (Boolean.Parse(node.InnerText) = value)以获得正确的结果。

答案 1 :(得分:0)

全部,而不是你的答案。我为我要说的话道歉。我发现了这个错误:它与我实现单例的方式有关。忘记将新创建的对象实例分配给共享变量。

Shared Function GetInstance() As GlobalController 
    If instance Is Nothing Then 
        instance = New GlobalController 
    End If 
    Return instance
End Function