C# Event事件

1. System.EventArgs

是一个预定义的框架类,除了静态的Empty属性之外,它没能其它成员
EventArgs是为事件传递信息的类的基类

2. PriceChangedEventArgs

  • 传递信息的类

根据所含有的信息进行命名,而不是所使用的事件
通常通过属性或只读字段来暴露数据

3. 为事件选择或定义一个委托

返回类型是void
接收两个参数,第一个参数类型是object,第二个参数类型是EventArgs的子类。第一个参数表示事件的广播者,第二个参数包含需要传递的信息
名称必须是以EventHandler结尾

Framework定义了一个范型委托System.EventHandler

public delegate void EventHandler
	(object source, TEventArgs e) where TEventArgs : EventArgs

4. 针对选择的委托定义事件

public class Stock
{
	...
	public event EventHandler PriceChanged;	
}

5. 可触发事件的protected virtual方法

  • 方法名必须和事件一致,前面再加上On,接收一个EventArgs参数
public class Stock
{
	...
	public event EventHandler PriceChanged;
	
	protected virtual void onPriceChanged(PriceChangedEventArgs e)
    {
    	PriceChanged?.Invoke(this, e);
    }
}

源码

using System;

namespace EventDemo
{
    public class PriceChangedEventArgs: EventArgs
    {
        public readonly decimal LastPrice;
        public readonly decimal NewPrice;

        public PriceChangedEventArgs(decimal lastPrice, decimal newPrice)
        {
            LastPrice = lastPrice;
            NewPrice = newPrice;
        }
    }

    class Stock
    {
        string symbol;
        decimal price;

        public Stock(string symbol)
        {
            this.symbol = symbol;
        }

        public event EventHandler PriceChanged;

        protected virtual void onPriceChanged(PriceChangedEventArgs e)
        {
            PriceChanged?.Invoke(this, e);
        }

        public decimal Price
        {
            get { return price; }
            set
            {
                if (price == value) return;
                decimal oldPrice = price;
                price = value;
                onPriceChanged(new PriceChangedEventArgs(oldPrice, price));
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Stock stock = new Stock("MORN");
            stock.Price = 160;
            stock.PriceChanged += stock_PriceChanged;
            stock.Price = 180;
        }

        static void stock_PriceChanged(object sender, PriceChangedEventArgs e)
        {
            if((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
            {
                Console.WriteLine("Alert, 10% stock price increase!");
            }
        }
    }
}

你可能感兴趣的:(C#)