选项严格的方法签名错误

时间:2014-09-28 07:15:29

标签: .net vb.net winforms methods method-signature

Option Strict会在这些签名中抛出一些错误:

Private Sub NotifyIcon_Systray_Click(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles RadMenuItem_Hide.Click,
        RadMenuItem_Show.Click,
        NotifyIcon_Systray.MouseDoubleClick

End Sub

Private Sub RadListControl_ProcessList_DoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles RadListControl_ProcessList.DoubleClick

End Sub

原始签名为:sender As Object, e as EventArgs但我将其更改为MouseEventArgs,因为我需要确定使用peoperty e.Button按下的按钮。

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您不能随意更改第二个参数的类型。 Click事件将EventArgs对象传递给其处理程序。更改参数类型不会神奇地改变该对象的类型。如果事件的签名与该参数匹配,则只能使用类型MouseEventArgs的参数。它适用于MouseClickMouseDoubleClick但不适用于ClickDoubleClick。你无法改变它。

答案 1 :(得分:2)

行为很奇怪,但您可以执行以下操作:

Option Strict On
Public Class Form1
    Private Event NewClick(sender As Object, e As MouseEventArgs)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        RaiseEvent NewClick(sender, CType(e, MouseEventArgs))
    End Sub

    Private Sub NewClickHandler(sender As Object, e As MouseEventArgs) Handles Me.NewClick
        MsgBox(e.X & "x" & e.Y & vbCrLf & e.Button.ToString)
    End Sub
End Class

您基本上处理了正确的签名,将e转换为MouseEventArgs,然后重新加载具有MouseEventArgs签名的自定义事件。

编辑: 我在System.Windows.Forms.Control课程中进行了一些挖掘,其原因在于,控件的OnClick事件实际上是使用MouseEventArgs引发的而不是简单的EventArgs {1}}。然后它会转换为EventArgs(显然自MouseEventArgs继承EventArgs后起作用)。

来自Control代码:

If flag AndAlso Not AddressOf Me.ValidationCancelled Then
    If Not Me.GetState(67108864) Then
        Me.OnClick(New MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(AddressOf m.LParam), NativeMethods.Util.SignedHIWORD(AddressOf m.LParam), 0))
        Me.OnMouseClick(New MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(AddressOf m.LParam), NativeMethods.Util.SignedHIWORD(AddressOf m.LParam), 0))
    Else
        '...
    End If
End If