我通常是一个c#程序员,但是现在我正在VB中为这个项目工作,当我用来设置一个单例类时,我将遵循Jon Skeet模型
public sealed class Singleton { static Singleton instance = null; static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { lock (padlock) { if (instance == null) { instance = new Singleton(); } return instance; } } } //Added to illistrate the point public static void a() { } public void b() { } }
或者现在的变化之一,如果我在c#
Singleton.Instance.什么程序是所有的成员不是静态的,而不是一个.
现在我在VB中做同样的事情
Private Shared _instance As StackTracker Private Shared ReadOnly _lock As Object = New Object() Private Sub New() _WorkingStack = New Stack(Of Methodobject) _HistoryStack = New Queue(Of Methodobject) End Sub Public Shared ReadOnly Property Instance() As StackTracker Get SyncLock _lock If (_instance Is nothing) Then _instance = New StackTracker() End If End SyncLock Return _instance End Get End Property
我得到StackTracker.Instance.Instance,它一直在继续,而不是世界的尽头,它看起来不错.
以下是完整的代码:
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