使用.net 3.5,我有一个工作表单,其中通过构造函数传递委托,例如:
Public Delegate Sub runDelegate(ByVal pId As String)
Private delgate As runDelegate
Public Sub New(ByVal dlg As runDelegate, ByVal pBtCaption As String)
' ...
If dlg IsNot Nothing Then
cbtRunOnSelected.Text = pBtCaption
cbtRunOnSelected.Visible = True
End If
delgate = dlg
End Sub
Private Sub cbtRunOnSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbtRunOnSelected.Click
delgate.Invoke(DirectCast(bs.Current, DataRowView)("id").ToString) 'call works
End Sub
但是我不想传递多个参数,而是希望将所有参数分组为一个对象(如果将来要添加它们,则更加灵活),所以我更改了代码:
Public Class cDelegate
Public Delegate Sub runDelegate(ByVal pId As String)
Public btCaption As String
End Class
Private delgate As cDelegate
Public Sub New( ByVal dlg As cDelegate)
' ...
If dlg IsNot Nothing Then
cbtRunOnSelected.Text = dlg.btCaption
cbtRunOnSelected.Visible = True
End If
delgate = dlg
End Sub
但是问题出在这里,该代码不起作用:
Private Sub cbtRunOnSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbtRunOnSelected.Click
delgate.runDelegate.Invoke(DirectCast(bs.Current, DataRowView)("id").ToString)
'error here
End Sub
通过实例访问共享成员,常量成员,枚举成员或嵌套类型;合格的表达式将不被评估。
答案 0 :(得分:1)
我希望这会有所帮助。我举了一个小例子来说明您所缺少的内容。具体来说,这是您将实际执行的方法。
委托是一种方法设计
委托实例是方法指针
您需要一个缺少的委托实例。这个例子应该可以帮助您看到
Public Class ClassName
Public Delegate Sub DelegateName(pId As String)
Public DelegateInstance As New DelegateName(AddressOf method)
Private Sub method(pId As String)
MessageBox.Show(pId)
End Sub
End Class
Private instance As ClassName
Public Sub New(classInstance As ClassName)
instance = classInstance
End Sub
Private Sub cbtRunOnSelected_Click(sender As Object, e As EventArgs) Handles Button1.Click
instance.DelegateInstance.Invoke("string")
End Sub
我更改了名字,因为您将所有委托都命名为委托,这令人困惑。