C#委托和事件机制

一、委托

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

namespace ConsoleCSharp
{
    public delegate void compute(int a, int b);
    class Program
    {
        static void Main(string[] args)
        {
            //compute c = add;
            compute c = new compute(add);
            c += mimus;
            c += multiply;
            c(3, 5);
        }

        public static void add(int a, int b)
        {
            Console.WriteLine("{0} add {1} is {2}", a, b, a + b);
        }

        public static void mimus(int a, int b)
        {
            Console.WriteLine("{0} mimus {1} is {2}", a, b, a - b);
        }

        public static void multiply(int a, int b)
        {
            Console.WriteLine("{0} multiply {1} is {2}", a, b, a * b);
        }
    }
}


二、事件

1、C#事件是特殊的委托
2、C#中使用委托模型来实现事件的。
3、C#中的委托是一个引用类型,可以把它看成一个特殊的”类”。

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

namespace ConsoleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            HumanResource hr = new HumanResource();
            MyEventArgs e = new MyEventArgs(12.25);
            emp.OnSalayCompute += new SalayCompute(hr.salayComputeHandle); //注册
            for ( ; ; )
            {
                Thread.Sleep(1000);
                emp.FireEvent(e);
            }
        }
    }

    public delegate void SalayCompute(object sender, MyEventArgs e); //声明一个代理类
    class Employee
    {
        public event SalayCompute OnSalayCompute; //定义事件,将其与代理绑定
        public void FireEvent(MyEventArgs e) //触发事件的方法
        {
            if (OnSalayCompute != null)
            {
                OnSalayCompute(this, e); //触发事件
            }
        }
    }

    public class MyEventArgs : EventArgs //定义事件参数类
    {
        public readonly double _salary;
        public MyEventArgs(double salary)
        {
            this._salary = salary;
        }
    }

    class HumanResource
    {
        //事件处理函数,签名应与代理一致
        public void salayComputeHandle(object sender, MyEventArgs e)
        {
            Console.WriteLine("salay: {0}", e._salary);
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值