我通常是一个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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。