C#之事件

 

简单的事件例子,需要的5个事件要素都在里面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、就是事件的拥有者
            Timer timer = new Timer();
            timer.Interval = 1000; //1秒钟
            //2、事件响应者
            Boy boy = new Boy();
            //3、事件订阅
            timer.Elapsed += boy.Action;
            //4、事件发布
            timer.Start();
            Console.ReadKey();

        }
    }

    class Boy
    {
        //5、事件处理器
        internal void Action(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Jump!");
        }
    }
}
using System;
using System.Windows.Forms;

namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、事件拥有者
            Form form = new Form();
            //2、事件响应者
            Controller controller = new Controller(form);
            form.ShowDialog();
           
            
        }
    }
    class Controller
    {
        private Form form;
        public Controller(Form form)
        {
            if (form != null)
            {
                this.form = form;
                //3、事件 + 4、事件的订阅
                this.form.Click += this.FormClicked;
            }
        }

        //5、事件都处理器
        private void FormClicked(object sender, EventArgs e)
        {
            this.form.Text = DateTime.Now.ToString();
        }
    }

}

 事件的拥有者同时也是事件的响应者

using System;
using System.Windows.Forms;

namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、事件的拥有者 + 2、事件的响应者
            MyForm form = new MyForm();
            //3、事件 + 4、事件的订阅者
            form.Click += form.Action;
            form.ShowDialog();
            Console.ReadKey();


        }

        //
        class MyForm : Form
        {
            //5、事件的处理器
            internal void Action(object sender, EventArgs e)
            {
                Console.WriteLine("MyForm");
                this.Text = DateTime.Now.ToString();
            }
        }
    }
}

事件的本身是类中的成员变量的例子

using System;
using System.Windows.Forms;

namespace EventExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MyForm form = new MyForm();
            form.ShowDialog();

        } 
    }
    class MyForm : Form
    {
        private TextBox textBox;
        //事件的拥有者
        private Button button;
        public MyForm()
        {
            this.textBox = new TextBox();
            this.button = new Button();
            this.button.Width = 100;
            this.button.Height = 100;
            this.button.Text = "Click Me";
            this.Controls.Add(this.textBox);
            this.Controls.Add(this.button);
            this.button.Click += this.ButtonClicked;
        }

        private void ButtonClicked(object sender, EventArgs e)
        {
            this.textBox.Text = "hello world~!!!!!!!!!!!!!!!!!!!!!!!!!";
        }
    }
}

自定义事件

using System;
using System.Threading;
using System.Windows.Forms;

namespace EventExample
{

    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            Waitor waitor = new Waitor();
            //事件 + 事件的订阅者
            customer.Order+=waitor.Action;
            customer.Action();
            customer.PayTheBill();
        }
    }
    public class OrderEventArgs : EventArgs
    {
        public string DishName { get; set; }
        public string Size { get; set; }
    }

    //声明一个委托
    public delegate void OrderEventHandler(Customer customer, OrderEventArgs e);

    //1、自定义一个事件的拥有者
    public class Customer
    {
        //声明事件处理器
        private OrderEventHandler orderEventHandler;
        
        public event OrderEventHandler Order
        {
            add
            {
                this.orderEventHandler += value;
            }
            remove
            {
                this.orderEventHandler -= value;
            }
        }
        public double Bill { get; set; }
        public void PayTheBill()
        {
            Console.WriteLine("I will pay ${0}", this.Bill);
        }
        public void Walkln()
        {
            Console.WriteLine("Walk into the restaurant");
        }
        public void SitDown()
        {
            Console.WriteLine("Sit Down");
        }
    public void Think()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("let me think...");
                Thread.Sleep(1000);
            }
            if (this.orderEventHandler != null)
            {
                OrderEventArgs e = new OrderEventArgs();
                e.DishName = "gongbaojiding";
                e.Size = "large";
                this.orderEventHandler.Invoke(this,e);
            }
        }

        public void Action()
        {
            Console.ReadLine();
            this.Walkln();
            this.SitDown();
            this.Think();
        }
    }
    //事件的响应者
    public class Waitor
    {
        internal void Action(Customer customer, OrderEventArgs e)
        {
            Console.WriteLine("I will serve you the dish-{0}", e.DishName);
            double price = 10;
            switch (e.Size)
            {
                case "small":
                    price = price * 0.5;
                    break;
                case "large":
                    price = price * 1.5;
                    break;
                default:
                    break;
            }
            customer.Bill += price;

        }
    }

}

最后的练习

   1、事件拥有者和事件响应者分别属于不同的类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.Control;

namespace ConsoleEventApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            /*Form form = new Form();
            Button button = new Button();
            TextBox textBox = new TextBox();
            button.Text = "Click Me";
            textBox.Width = 200;
            ControlCollection c = form.Controls;
            c.Add(button);
            c.Add(textBox);
            Console.WriteLine(c);
            form.ShowDialog();
            Console.ReadKey();*/

            //1、事件拥有者和事件响应者分别属于不同的类:
            Form form = new Form(); //事件拥有者
            myForm myform = new myForm(form); //事件响应者
            form.ShowDialog();//显示窗体
        }
    }

    //事件响应者
    class myForm
    {
        //事件成员
        public Form form;
        public myForm(Form form)
        {
            if(form != null)
            {
                this.form = form;
                //事件订页
                this.form.Click += FormClicked;
            }
        }

        //事件处理器
        private void FormClicked(object sender, EventArgs e)
        {
            
            this.form.Text = DateTime.Now.ToString();
        }
    }
}

2、事件拥有者和事件响应者是同一个对象

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            MyForm form = new MyForm(); //事件拥有者和事件响应者皆为form
            form.Click += form.FormClicked; //事件Click,事件处理器FormClicked,事件订阅+=
            form.ShowDialog();
            //假如这里写成:
            //Form form = new Form();
            //form.Click += form.FormClicked;
            //“FormClicked”的实现部分无法由编译器自动生成
            //因为Form是系统提供的类,我们无法随意更改,
            //所以就不能像之前一样用编译器去给事件处理器自动生成方法
            //这就需要我们自己写一个类去继承(class MyForm : Form)
        }
        
    }
    class MyForm : Form
    {
        //事件处理器
        internal void FormClicked(object sender, EventArgs e)
        {
            this.Text = "Hello World!";
        }
    }
}

3、事件拥有者是事件响应者的一个字段,或事件响应者是事件拥有者的一个字段       

这是WinForm编程中常用的一种方式,比如在一个窗体中,存在一个文本框和按钮,现在要通过点击按钮让文本框上显示出文字“Hello World”。

发生的事件是:鼠标点击;事件拥有者是:按钮(Button),鼠标点击的是它,它是窗体对象的一个字段成员;事件响应者是窗体对象;事件处理是:窗体对象让自己的字段成员文本框

4、自定义事件

using System;
using System.Threading;

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer(); //事件拥有者
            Waiter waiter = new Waiter(); //事件响应者
            customer.Order += waiter.Action; //事件Order,事件处理器Action,事件订阅+=
            customer.OrderingProcess(); //触发事件,模拟顾客点菜过程
        }
    }

    //用于传递事件参数(事件信息)的类
    public class OrderEventArgs : EventArgs
    {
        public String DishName { get; set; } //表示菜名
        public String Size { get; set; } //表示规格
    }
    
    //声明委托类型(事件订阅)
    //第1个参数为事件拥有者,第2个参数是用来存储点菜事件的相关信息(事件参数)
    public delegate void OrderEventHandler(Customer customer,OrderEventArgs e);
    
    //顾客类:事件拥有者
    public class Customer
    {
        //根据前面声明的委托类型来创建一个委托类型字段,用来引用事件处理器
        private OrderEventHandler orderEventHandler;
        //声明事件:
        //event为事件关键字,OrderEventHandler表示用此委托来约束该事件
        public event OrderEventHandler Order
        {
            //添加事件处理器
            add
            {
                orderEventHandler += value;
            }
            //删除事件处理器
            remove
            {
                orderEventHandler -= value;
            }
        }
        //模拟顾客点菜过程:
        public void OrderingProcess()
        {
            Console.WriteLine("输入回车后开始进行模拟");
            Console.ReadLine();
            Console.WriteLine("顾客进入餐馆");
            Thread.Sleep(1000);
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("顾客点菜中...");
                Thread.Sleep(1000);
            }
            //触发事件:
            if (orderEventHandler != null) //若不存在任何事件处理器则无法触发事件
            {
                //准备好事件参数
                OrderEventArgs e = new OrderEventArgs();
                e.DishName = "饺子";
                e.Size = "大份的";
                //调用事件处理器
                orderEventHandler(this,e);
            }
        }
    }

    //侍者类:事件响应者
    public class Waiter
    {
        public void Action(Customer customer, OrderEventArgs e)
        {
            double price = 0;
            //根据规格计算价格
            switch (e.Size)
            {
                case "小份的":
                    price = 5;
                    break;
                case "中份的":
                    price = 10;
                    break;
                case "大份的":
                    price = 15;
                    break;
            }
            Console.WriteLine("服务员:好的,稍后将为您提供一份" 
                + e.Size + e.DishName + ",您一共需要支付" + price + "元。");
        }
    }
}

//运行结果:
输入回车后开始进行模拟

顾客进入餐馆
顾客点菜中...
顾客点菜中...
顾客点菜中...
服务员:好的,稍后将为您提供一份大份的饺子,您一共需要支付15元。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值