是否有单身人士引发事件?

时间:2017-11-24 01:48:58

标签: vb.net

我有一个单例类,但我希望它的对象能够引发事件。 我目前的单例代码如下:

Private Shared ReadOnly _instance As New Lazy(Of WorkerAgent)(Function() New _
    WorkerAgent(), LazyThreadSafetyMode.ExecutionAndPublication)

Private Sub New()
End Sub

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

每当我将ReadOnly _instance As New..更改为ReadOnly WithEvents _instance As New...

我收到错误ReadOnly is not valid on a WithEvents deceleration

虽然我可以在属性本身中创建实例,但我喜欢上面的代码,因为它使用的是.NET Lazy关键字,它可能具有很好的多线程优势。

1 个答案:

答案 0 :(得分:0)

这不是问题的答案,但它证明了为什么这个问题没有意义。它还需要相当多的代码,因此在评论中发布并不是一个真正的选择。这就是你的单例类如何引发事件,就像任何其他类一样,以及消费者如何处理这些事件,就像任何其他类型一样。

的Singleton:

Public Class WorkerAgent

    Private Shared ReadOnly _instance As New Lazy(Of WorkerAgent)

    Private _text As String

    Public Shared ReadOnly Property Instance As WorkerAgent
        Get
            Return _instance.Value
        End Get
    End Property

    Public Property Text As String
        Get
            Return _text
        End Get
        Set
            If _text <> Value Then
                _text = Value
                OnTextChanged(EventArgs.Empty)
            End If
        End Set
    End Property

    Public Event TextChanged As EventHandler

    Private Sub New()
    End Sub

    Protected Overridable Sub OnTextChanged(e As EventArgs)
        RaiseEvent TextChanged(Me, e)
    End Sub

End Class

请注意,实例属性更改时会引发实例事件,就像其他任何类型的单例一样,都会引发实例事件。

消费者:

Public Class Form1

    Private WithEvents agent As WorkerAgent = WorkerAgent.Instance

    Private Sub agent_TextChanged(sender As Object, e As EventArgs) Handles agent.TextChanged
        '...
    End Sub

End Class

分配单个实例的字段是使用WithEvents的位置。正如您的错误消息所述,该字段也无法声明ReadOnly。如果他们想要ReadOnly字段,那么他们需要使用AddHandler来处理事件。

相关问题