介绍使用系统;
公开课TestEventArgs: EventArgs
{
公共TestEventArgs():基础(){}
公共字符串消息{;设置;}
}
小编给大家分享一下c#在程序中定义和使用自定义事件的方法,希望大家阅读完这篇文章后大所收获、下面让我们一起去探讨吧!
c#在程序中定义和使用自定义事件的步骤有:首先在类中定义事件,然后再定义事件的参数,在TestClass中来引发事件最后使用事件
c#在程序中定义和使用自定义事件可以分为以下几个步骤:
<强>步骤1:在类中定义事件强>
使用系统; 公开课TestClass {//? 公共事件EventHandler TestEvent }
<>强步骤2:定义事件参数强>
注意:事件参数类TestEventArgs继承自系统。以前EventArgs
<>强步骤3:在TestClass引发事件强>
TestClass公共类 {//这个方法引发事件 公共空间RaiseTestEvent(字符串消息) { 如果(TestEvent==null)返回; TestEvent(这一点,新的TestEventArgs{消息=消息}); } 公共事件EventHandler TestEvent; }
<>强步骤4:使用事件强>
类项目 { 静态void Main (string [] args) { TestClass tc=new TestClass ();//挂接事件处理方法 tc。TestEvent +=Tc_TestEvent; Console.WriteLine(“按任意键引发事件“); Console.ReadKey ();//引发事件 tc.RaiseTestEvent(“通过事件参数传递的字符串“); Console.WriteLine(“按任意键退出“); Console.ReadKey (); } 私有静态孔隙Tc_TestEvent(对象发送方,EventArgs e) {//将事件参数强制转换为TestEventArgs TestEventArgs te=(TestEventArgs);//显示事件参数中的消息 Console.WriteLine (te.Message); } }
<>强完整的程序如下强>
使用系统; 公开课TestClass { 公共空间RaiseTestEvent(字符串消息) { 如果(TestEvent==null)返回; TestEvent(这一点,新的TestEventArgs{消息=消息}); } 公共事件EventHandler TestEvent; } 公开课TestEventArgs: EventArgs { 公共TestEventArgs():基础(){} 公共字符串消息{;设置;} } 类项目 { 静态void Main (string [] args) { TestClass tc=new TestClass (); tc。TestEvent +=Tc_TestEvent; Console.WriteLine(“按任意键引发事件“); Console.ReadKey (); tc.RaiseTestEvent(“通过事件参数传递的字符串“); Console.WriteLine(“按任意键退出“); Console.ReadKey (); } 私有静态孔隙Tc_TestEvent(对象发送方,EventArgs e) { TestEventArgs te=(TestEventArgs); Console.WriteLine (te.Message); } }
看完了这篇文章,相信你对c#在程序中定义和使用自定义事件的方法有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!