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);

一、委托

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);
        }
    }
}


目录
相关文章
|
C#
C# 委托和事件
C# 委托和事件
80 0
C# 委托和事件
一个插排引发的设计思想 (三) 委托与事件
一个插排引发的设计思想 (三) 委托与事件
86 0
|
Web App开发 安全 C#
|
监控 C# Windows
|
JavaScript 前端开发
事件代理和委托学习
参考资料:           又被事件冒泡坑了一把,这次要彻底弄懂浏览器的事件流           JavaScript事件代理和委托 事件委托:   实际案例:我们平时在开发时,有这种情况,一个ul里有有好多个li子元素,这个li的数量可以是固定的,也可以是动态添加删除的,而且每个li...
968 0
|
C#
大白话系列之C#委托与事件讲解(一)
    从序言中,大家应该对委托和事件的重要性有点了解了吧,虽然说我们现在还是能模糊,但是从我的大白话系列中,我会把这些概念说的通俗易懂的。首先,我们还是先说说委托吧,从字面上理解,只要是中国人应该都知道这个意思,除非委托2个中文字不认识,举个例子,小明委托小张去买车票。
1161 0