【问题标题】:Keep address of sub in property在属性中保留子的地址
【发布时间】:2016-07-30 14:25:33
【问题描述】:

我将使用属性来保存单击子的地址,然后将其分配给 AddRow() 子中的每个按钮。当我收到以下错误时出现问题:

错误 1

方法 'Public Property ClickEvent As Button_Click' 没有 签名兼容委托“委托子事件处理程序(发件人 作为对象,e 作为 System.EventArgs)'。

Private Sub Button_Click(sender As Object, e As EventArgs)
    'do somthing
End Sub

Class CustomClass
    Public Fields As New List(Of FieldsDefinition)()

    Class FieldsDefinition
        Public Delegate Sub Button_Click(sender As System.Object, e As System.EventArgs)

        Public __ClickEventValue As Button_Click
        Public Property ClickEvent() As Button_Click
            Get
                Return __ClickEventValue
            End Get

            Set(ByVal value As Button_Click)
                __ClickEventValue = value
            End Set
        End Property
    End Class

    Public Sub AddRow()
        For Each field As FieldsDefinition In Fields
            Dim ctrl As New TextBox
            AddHandler ctrl.Click, AddressOf field.ClickEvent
        Next
    End Sub
End Class

【问题讨论】:

    标签: .net vb.net properties delegates


    【解决方案1】:

    2 个变化:

    1. 删除AddressOf,因为您不希望处理程序成为ClickEvent 属性本身,而是希望它成为返回的委托。

    2. AddHandler 将需要 EventHandler 类型的处理程序。因此,删除Button_Click 委托声明,并将对它的所有引用替换为EventHandler

    代码:

    Private Sub Button_Click(sender As Object, e As EventArgs)
        'do somthing
    End Sub
    
    Class CustomClass
        Public Fields As New List(Of FieldsDefinition)()
    
        Class FieldsDefinition
            ' removed Button_Click delegate declaration here
    
            Public __ClickEventValue As EventHandler 'changed Button_Click to EventHandler here
            Public Property ClickEvent() As EventHandler 'changed Button_Click to EventHandler here
                Get
                    Return __ClickEventValue
                End Get
    
                Set(ByVal value As EventHandler) 'changed Button_Click to EventHandler here
                    __ClickEventValue = value
                End Set
            End Property
        End Class
    
        Public Sub AddRow()
            For Each field As FieldsDefinition In Fields
                Dim ctrl As New TextBox
                AddHandler ctrl.Click, field.ClickEvent 'removed AddressOf here
            Next
        End Sub
    End Class
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2014-07-05
      • 2014-05-06
      相关资源
      最近更新 更多