VB.NET事件通道的实现,可以通过多个类的操作来进行实现。对于初学者来说,这一技巧的应用往往会给他们在实际应用中带来一定的麻烦。下面就为大家详细解读一下具体的操作步骤,以方便大家参考学习。
C#代码示例如下:
- public delegate void showMsg
- EventHandler(string msg);
- class msg
- {
- public event showMsgEvent
Handler showMsgEvent;
public string execMsg(string msg)- {
- if (showMsgEvent != null)
- {
- showMsgEvent(msg + "," +
DateTime.Now.ToString());- }
- return string.Empty;
- }
- }
- ===调用===
- int i = 3;
- msg[] myMsg;
- private void button2_Click
(object sender, EventArgs e)- {
- myMsg = new msg[i];
- for(int j=0;j<i;j++)
- {
- myMsg[j]=new msg();
- myMsg[j].showMsgEvent +=new
showMsgEventHandler(Form3_
showMsgEvent);- }
- }
- void Form3_showMsgEvent (string msg)
- {
- MessageBox.Show(msg);
- }
- private void button3_Click
(object sender, EventArgs e)- {
- for (int j = 0; j < i; j++)
- {
- myMsg[j].execMsg("good "
+ j.ToString());- }
- }
转换后的VB.NET事件通道代码:
- Delegate Sub showMsgEventHandler
()Sub showMsgEventHandler
(ByVal msg As String)- Class msgClass msg
- Public name As String
- Event msgEvent As showMsg
EventHandler- Public Sub showMsg()Sub showMsg
(ByVal msg As String)- MsgBox(msg + DateTime.Now.
ToString() + " ," + name)- End Sub
- End Class===调用===
- Dim i As Integer = 0
- Dim myContain As New List(Of msg)
- Private Sub Button2_Click(
)Sub Button2_Click(ByVal sender
As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click- For i = 0 To 3 Step 1
- Dim myMsg As New msg
- myMsg.name = "name" & i.ToString()
- myContain.Add(myMsg)
- AddHandler myMsg.msgEvent,
New showMsgEventHandler(AddressOf
responseMsg)- Next i
- End Sub
- Private Sub responseMsg()Sub
responseMsg(ByVal msg As String)- MsgBox(msg)
- End Sub
- Private Sub Form1_Load()Sub Form1_Load
(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles MyBase.Load- End Sub
- Private Sub Button3_Click()Sub
Button3_Click(ByVal sender As
System.Object, ByVal e As System.
EventArgs) Handles Button3.Click- For i = 0 To 3 Step 1
- Dim myMsg As New msg
- myMsg = myContain.Item(i)
- myMsg.showMsg("good ")
- Next i
- End Sub
VB.NET事件通道相关共用方法就为大家介绍到这里。
【编辑推荐】