H_J_H

------专用杂物房
posts - 26, comments - 1, trackbacks - 0, articles - 119

[导入]事件

Posted on 2006-04-26 21:17 H_J_H 阅读(61) 评论(0)  编辑 收藏 引用
    事件是windows编程中很重要的一个概念。

   在事件通信机制中,事件发送方不知道哪个对象或方法将接收到它引发的事件以及进行什么样的响应,它只是将“事件发生了”这个消息广播出去。

   C#中,事件机制是借助委托来实现的,我们可以通过实例来认识事件。

   如同字段、属性、方法等一样,事件也是类的成员。

   关键字event用来定义事件,并且在定义事件时,要使用到事先定义好的一个委托

例:

using System;

 

namespace shijian

{

    class Class1

    {

        [STAThread]

        static void Main(string[] args)

        {

            MyClass c = new MyClass();

            c.CalaculateFinished += new MyDelegate(c_CalaculateFinished);

            c.Square(2);

            c.Cube(2);

            c.Double(2);

        }

 

        private static void c_CalaculateFinished(string msg)//事件处理方法

        {

            Console.WriteLine(msg + "计算机完成!");

        }

    }

    delegate void MyDelegate(string msg);//定义委托

 

    class MyClass

    {

        public event MyDelegate CalaculateFinished;//定义事件

 

        public void OnCalaculateFinished(string msg)//触发事件

        {

            if (CalaculateFinished != null)

            {

             CalaculateFinished(msg);//更确切的说,它才是实现了触发了事件

            }

        }

 

        public void Square(float x)

        {

            float result = x * x;

            Console.WriteLine("{0}的平方等于:{1}",x,result);

            OnCalaculateFinished("平方");

        }

 

        public void Cube(float x)

        {

            float result = x * x * x;

            Console.WriteLine("{0}的立方等于:{1}",x,result);

            OnCalaculateFinished("立方");

        }

 

        public void Double(float x)

        {

            float result = 2 * x;

            Console.WriteLine("{0}的倍数等于:{1}",x,result);

            OnCalaculateFinished("倍数");

        }

    }

}



sopper 2006-04-13 16:36

文章来源:http://sopper.cnblogs.com/archive/2006/04/13/374403.html
只有注册用户登录后才能发表评论。