在基类中实现事件

时间:2010-11-15 14:56:27

标签: vb.net oop events

考虑以下对象:

Public MustInherit Class FileRepository

    Public MustOverride Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)

    Public Event FileSaved(ByRef sender As Object, ByVal EventArgs As EventArgs)

End Class

Public Class XMLFileRepository
    Inherits FileRepository

    Public Overrides Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)

    End Sub

    Private Sub XMLFileRepository_FileSaved(ByRef sender As Object, ByVal EventArgs As System.EventArgs) Handles Me.FileSaved

    End Sub
End Class

我希望我的基类在保存文件后在其FileSaved的实现中引发SaveStringToFile事件。但是在VB.NET中,您不能让派生类引发基类事件。我想我可以将XMLFileRepository_FileSaved视为标准函数调用,并让我的SaveStringToFile实现直接调用它,但我认为我正在以错误的方式处理问题。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:3)

在基类中添加一个可覆盖的子类,用于引发基类FileSaved-Event:

Public MustInherit Class FileRepository

    Public MustOverride Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)

    Public Event FileSaved(ByVal FileText As String, ByVal FilePath As String)

    Protected Overridable Sub OnFileSaved(ByVal FileText As String, ByVal FilePath As String)
        RaiseEvent FileSaved(FileText, FilePath)
    End Sub

End Class

Public Class XMLFileRepository
    Inherits FileRepository

    Public Overrides Sub SaveStringToFile(ByVal FileText As String, ByVal FilePath As String)
        MyBase.OnFileSaved(FileText, FilePath)
    End Sub

    Private Sub XMLFileRepository_FileSaved(ByVal FileText As String, ByVal FilePath As String) Handles MyBase.FileSaved

    End Sub
End Class