vb.net中的事件 ''' <summary> ''' 申明代理 ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Delegate Sub myEvnetHandler()Sub myEvnetHandler(ByVal sender As Object, ByVal e As EventArgs)
''' <summary> ''' 創建事件發布者類,所需做的事情有: ''' 1、申明事件 ''' 2、檢測事件是事存在的方法(可有可無) ''' 3、事件調用 ''' </summary> ''' <remarks></remarks> Class ReleaseClass Release Public Event myEvent As myEvnetHandler Public Sub DomyEvent()Sub DomyEvent() RaiseEvent myEvent(Nothing, Nothing) End Sub End Class
''' <summary> ''' 創建事件接收者類,所需做的事情: ''' 利用代理將對象及其方法注冊進事件 ''' </summary> ''' <remarks></remarks> Class ReceiveClass Receive Public Sub New()Sub New(ByVal rl As Release) AddHandler rl.myEvent, AddressOf OnmyEvent End Sub Sub OnmyEvent()Sub OnmyEvent(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("VB Event Raise") Console.ReadLine() End Sub End Class
''' <summary> ''' 實例化發布者、訂閱者類,並引發事件 ''' 事件只能還發布者調用,接收者注冊 ''' </summary> ''' <remarks></remarks> Module Module1Module Module1 Sub Main()Sub Main() Dim R As Release = New Release() Dim C As Receive = New Receive(R) R.DomyEvent() End Sub End Module
C#中事件 using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication1 { /**//// <summary> /// 申明代理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> delegate void myEventHandler(object sender,EventArgs e);
/**//// <summary> /// 創建事件發布者類,所需做的事情有: /// 1、申明事件 /// 2、檢測事件是事存在的方法(可有可無) /// 3、事件調用 /// </summary> class Release { public event myEventHandler myEvent; public void DomyEvent() { if (myEvent != null) { myEvent(null, null); } } }
/**//// <summary> /// 創建事件接收者類,所需做的事情: /// 利用代理將對象及其方法注冊進事件 /// </summary> class Receive { public Receive(Release rl) { rl.myEvent += new myEventHandler(rl_myEvent); }
void rl_myEvent(object sender, EventArgs e) { Console.WriteLine("C# Event Raised"); Console.ReadLine(); } }
/**//// <summary> /// 實例化發布者、訂閱者類,並引發事件 /// 事件只能還發布者調用,接收者注冊 /// </summary> class Program { static void Main(string[] args) { Release R = new Release(); Receive C = new Receive(R); R.DomyEvent(); } } }
|
请发表评论