时间:2010-07-23 14:30:45

标签: vb.net singleton

4 个答案:

答案 0 :(得分:12)

这是完整的代码:

Public NotInheritable Class MySingleton
    Private Shared ReadOnly _instance As New Lazy(Of MySingleton)(Function() New
        MySingleton(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance() As MySingleton
        Get
            Return _instance.Value
        End Get
    End Property
End Class

然后使用此类,使用:

获取实例
Dim theSingleton As MySingleton = MySingleton.Instance

答案 1 :(得分:5)

答案 2 :(得分:3)

最初的问题不是关于如何实现单例模式,而是指在C#中尝试通过实例访问静态成员的编译器错误。在当前的VB中它是一个警告。

<强>解决方案: 您可以将项目编译器设置更改为&#34;将所有警告视为错误&#34;,但我不知道如何将警告42025明确地视为错误。

话虽如此,在VB中实现单例的方法也更为简单:

public class Singleton
    private sub new()
    end sub

    public shared readonly property Instance as Singleton
        get
            static INST as Singleton = new Singleton
            return INST
        end get
    end property
end class

这依赖于静态变量的VB线程安全单一初始化,这是C#中没有的功能。以&#34; static&#34;开头的代码行即使从许多线程多次访问Instance属性,也只评估一次。

答案 3 :(得分:0)

也许我遗漏了一些东西,但我只是对此做了一些改动,这取决于班级中发生的其他事情:

Class MySingleton

    'The instance initializes once and persists (provided it's not intentionally destroyed)
    Private Shared oInstance As MySingleton = New MySingleton

    'A property initialized via the Create method
    Public Shared Property SomeProperty() As Object = Nothing

   'Constructor cannot be called directly so prevents external instantiation
    Private Sub New()
        'Nothing to do
    End Sub

    'The property returns the single instance
    Public Shared ReadOnly Property Instance As MySingleton
        Get
            Return oInstance
        End Get
    End Property

    'The method returns the single instance while also initializing SomeProperty
    Public Shared Function Create(
        ByVal SomeParam As Object) As MySingleton

        _SomeProperty = SomeParam
        Return oInstance
    End Function
End Class

很显然,您通常只提供 Instance属性 Create方法,但不能同时提供两者(尽管您可以提供)出于某种原因)。

最简单的形式是:

Class MySingleton

    Private Shared oInstance As MySingleton = New MySingleton

    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance As MySingleton
        Get
            Return oInstance
        End Get
    End Property
End Class