惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
T
Tailwind CSS Blog
博客园_首页
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
J
Java Code Geeks
量子位
D
DataBreaches.Net
MongoDB | Blog
MongoDB | Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
C
Check Point Blog
V
Visual Studio Blog
H
Help Net Security
Recent Announcements
Recent Announcements
Engineering at Meta
Engineering at Meta

博客园 - 言午

Nopcommerce 二次开发2 Admin Nopcommerce 二次开发1 基础 Nopcommerce 二次开发2 WEB Nopcommerce 二次开发0 sqlce中不支持sp_rename修改表名 C#读取Excel遇到无法读取的解决方法 狼奔代码生成器 银行账户类 累 interface 抽象类 抽象方法 Message 类的继承 多态(虚方法) 委托 代理 索引! 第五周作业 第四周作业 考试! 线程安全 二 线程安全 一
事件event
言午 · 2012-04-11 · via 博客园 - 言午

委托,是事件基础

类的对象,发出消息,在运行时绑定处理方法。

以下,以animal为例,体温过高时,触发事件

1 先定一个个委托

delegate void MyDelegate();

2 在类中定义事件,并在某时刻触发。此例中在体温属性改变,大于37.5时触发。

    

class Animal
    {
        // 定义一个事件 体温过高  (先定义MyDelegate)
        public event MyDelegate highTemperature;
        float temperature;//体温

        public float Temperature
        {
            get { return temperature; }
            set
            {
                temperature = value; 
                //体温高时,触发事件。事件,一般在属性改变时触发
                if (temperature > 37.5)
                {
                    highTemperature();
                }
            }
        }      
    }

3 使用事件时,要将事件与处理事件的方法关联,然后改变属性触发事件。

定义一个方法,热了,就开空调

        

static void a_highTemperature()
        {
            Console.WriteLine("开空调");
        }

然后在main方法中写

            Animal a = new Animal();
            a.highTemperature += new MyDelegate(a_highTemperature); //事件 --- 处理方法
            a.Temperature = 37.6f;