重载VB.NET事件?

时间:2014-06-06 05:07:27

标签: vb.net class

在我的VB.NET课程中,我有一些像这样的代码:

Public Class barClass

Private Function foo(data as string)
    msgbox("Data is a string: " & data)
End Function

Private Function foo(data as integer)
    msgbox("Data is an integer: " & data
End Function

End Class

这显然允许您传递foo字符串或整数。

我想我可以为事件做同样的事情,所以我试试:

Public Event FooRaised(data as string)
Public Event FooRaised(data as integer)

我认为这会让我通过传递foo得到的任何数据来引发事件,但是我得到一个错误,说我不能这样做(已经宣布了FooRaised)。 / p>

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

使用Object参数声明单个事件,然后检查类型以处理它:

Public Class Form1

  Public Event Foo(o As Object)

  Sub FooHandler(o As Object) Handles Me.Foo
    If o.GetType Is GetType(Integer) Then
      Dim i As Integer = DirectCast(o, Integer)
      i += 1 'add one to the integer value'
      MsgBox(i.ToString)
    ElseIf o.GetType Is GetType(String) Then
      Dim s As String = DirectCast(o, String)
      s &= "!!" 'append exclamation marks'
      MsgBox(s)
    End If
  End Sub

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RaiseEvent Foo(21)
    RaiseEvent Foo("a string value")
  End Sub
End Class