委托(deldgate)最大的用处是不是在多线程的处理?
RT,当然不算委托用在“事件”处理方面的作用。在我来看,如果在单线程的情况下,使用委托最大的作用就是回调(方便使相同的方法返回到不同的位置)。可是这个功能也可以使用其他方法轻松实现。所以在一般情况下,委托是不是没什么作用?
以下的代码是实现单击按钮后内容在不同textbox里面出现,但是使用了委托就更麻烦了,可读性也差。
例如:
Public Class Form1
'在注释中的这些代码可以很简单的实现目标。
'Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click, Button1.Click
' Dim test As New TestDeleg
' Dim button As Button = CType(sender, Button)
' If button.Name Is "Button1" Then
' TextBox1.Text = Label1.Text
' Else
' TextBox2.Text = Label1.Text
' End If
'End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim test As New TestDeleg
test.Display(label1.Text,addressof WriteT1)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button2.Click
Dim test As New TestDeleg
test.Display (label1.Text ,addressof writeT2)
End Sub
Private Sub WriteT1(ByVal str As String)
TextBox1.Text = str
End Sub
Private Sub WriteT2(ByVal str As String)
TextBox2.Text = str
End Sub
End Class
Friend Class TestDeleg
Public Delegate Sub delegSUB(ByVal str As String)
Public Sub Display(ByVal str As String, ByVal deleg2 As delegSUB)
deleg2(str)
End Sub
End Class