栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在C#中创建自己的事件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在C#中创建自己的事件?

这是使用C#创建和使用事件的示例

using System;namespace Event_Example{    //First we have to define a delegate that acts as a signature for the    //function that is ultimately called when the event is triggered.    //You will notice that the second parameter is of MyEventArgs type.    //This object will contain information about the triggered event.    public delegate void MyEventHandler(object source, MyEventArgs e);    //This is a class which describes the event to the class that recieves it.    //An EventArgs class must always derive from System.EventArgs.    public class MyEventArgs : EventArgs    {        private string EventInfo;        public MyEventArgs(string Text)        { EventInfo = Text;        }        public string GetInfo()        { return EventInfo;        }    }    //This next class is the one which contains an event and triggers it    //once an action is performed. For example, lets trigger this event    //once a variable is incremented over a particular value. Notice the    //event uses the MyEventHandler delegate to create a signature    //for the called function.    public class MyClass    {        public event MyEventHandler OnMaximum;        private int i;        private int Maximum = 10;        public int MyValue        { get {     return i; } set {     if(value <= Maximum)     {         i = value;     }     else     {         //To make sure we only trigger the event if a handler is present         //we check the event to make sure it's not null.         if(onMaximum != null)         {  onMaximum(this, new MyEventArgs("You've entered " +      value.ToString() +      ", but the maximum is " +      Maximum.ToString()));         }     } }        }    }    class Program    {        //This is the actual method that will be assigned to the event handler        //within the above class. This is where we perform an action once the        //event has been triggered.        static void MaximumReached(object source, MyEventArgs e)        { Console.WriteLine(e.GetInfo());        }        static void Main(string[] args)        { //Now lets test the event contained in the above class. MyClass MyObject = new MyClass(); MyObject.onMaximum += new MyEventHandler(MaximumReached); for(int x = 0; x <= 15; x++) {     MyObject.MyValue = x; } Console.ReadLine();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408367.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号