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


目录
相关文章
|
5月前
|
存储 安全 C#
C# - 委托与事件
这篇文档介绍了C#中的委托和事件。委托是存储方法引用的类型,支持回调、事件处理,具有引用方法、类型安全、多播性等特性,并在异步编程中发挥作用。事件是委托的封装,提供保护和订阅机制,防止外部直接访问。当需要在类内部控制方法调用,防止外部误触发时,可使用事件。
|
C#
C# 委托和事件
C# 委托和事件
94 0
C# 委托和事件
一个插排引发的设计思想 (三) 委托与事件
一个插排引发的设计思想 (三) 委托与事件
98 0
|
Web App开发 安全 C#
|
监控 C# Windows
|
JavaScript 前端开发
事件代理和委托学习
参考资料:           又被事件冒泡坑了一把,这次要彻底弄懂浏览器的事件流           JavaScript事件代理和委托 事件委托:   实际案例:我们平时在开发时,有这种情况,一个ul里有有好多个li子元素,这个li的数量可以是固定的,也可以是动态添加删除的,而且每个li...
995 0