加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#中实现自定义事件的代码演示

发布时间:2020-12-15 17:55:28 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 事件是C#中一个重要的内容,MSDN上有一个自定义事件的演示示例。我看了半天有点晕,所以新建了一个winform工程添加了一个按钮,然后找出调用的程序,

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

事件是C#中一个重要的内容,MSDN上有一个自定义事件的演示示例。我看了半天有点晕,所以新建了一个winform工程添加了一个按钮,然后找出调用的程序,一对比做了一个类似的示例,就明白了。看代码有时候比看文档来得更快。
using System;
 
namespace TestEventArgs
{
    /// <summary>
    /// 这个类对应于EventArgs,做对比学习。
    /// 添加两个内容:info1,info2。
    /// </summary>
    public class MyEventArgs : EventArgs
    {
        private String info1;
        private UInt32 info2;
 
        public MyEventArgs(String info1,UInt32 info2)
        {
            this.info1 = info1;
            this.info2 = info2;
        }
 
        public String Info1
        {
            get { return this.info1; }
            set { this.info1 = value; }
        }
 
        public UInt32 Info2
        {
            get { return this.info2; }
            set { this.info2 = value; }
        }
    }
 
    /// <summary>
    /// 仿真Button按钮
    /// </summary>
    public class MyButton
    {
        public delegate void MyEvnetHandler(object sender,MyEventArgs e);
        /// <summary>
        /// 按钮点击的次数计数器
        /// </summary>
        public static UInt32 clicked_num = 0;
        public event MyEvnetHandler MyClick;
 
        public void 触发()
        {
            MyEventArgs arg = new MyEventArgs(DateTime.UtcNow.ToString(),++clicked_num);
            MyClick(this,arg);
        }
    }
 
    /// <summary>
    /// 仿真Form窗体
    /// </summary>
    public class MyForm
    {
        public MyButton 按钮;
        public MyForm()
        {
            按钮 = new MyButton();
            按钮.MyClick += new MyButton.MyEvnetHandler(this.button_Clicked);
        }
 
 
        public void button_Clicked(object sender,MyEventArgs e)
        {
            Console.WriteLine("button clicked(sender is:" + sender.ToString() + "; info1 = "
                + e.Info1 + "; info2 = " + e.Info2);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            MyForm 窗体 = new MyForm();
            for (int i = 0; i < 10; i++ )
            {
                窗体.按钮.触发();
                System.Threading.Thread.Sleep(500);
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

不同的地方:
1?本示例中delegate?myevnethandler是mybutton类内部成员,在系统中eventhander是system命名空间下的一个成员。

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读