码迷,mamicode.com
首页 > Windows程序 > 详细

C#的事件

时间:2015-08-31 06:27:07      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace codeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            EventTest e = new EventTest(10);
            e.eNumDelegate += new codeTest.EventTest.NumDelegate(e.Show);
            e.eNumDelegate += (x) => { Console.WriteLine("匿名函数可以直接绑定!"); };
            e.SetValue(20);

            IEvent ie= new MyClass();
            ie.myDelegate += new MyDelegate(show);
            ie.Show();
            ie.myEventHandler += new EventHandler(Show);
            ie.myEventHandler(new object(), new EventArgs());
            Console.ReadLine();
        }

        static void show()
        {
            Console.WriteLine("Show!!!");
        }

        static void Show(object sender, EventArgs e)
        {
            Console.WriteLine("Show EventHandler");
        }
    }

    class EventTest
    {
        int value;
        public delegate void NumDelegate(int num);
        public event NumDelegate eNumDelegate;
        public EventTest(int num)
        {
            SetValue(num);
        }

        public void OnNumChange(int num)
        {
            if (eNumDelegate != null)
            {
                eNumDelegate(num);
            }
            else
            {
                Console.WriteLine("Event is null");
            }
        }

        public void SetValue(int n)
        {
            if (value != n)
            {
                value = n;
                OnNumChange(n);
            }
        }

        public void Show(int num)
        {
            Console.WriteLine(string.Format("Num is {0}", num));
        }
    }

    public delegate void MyDelegate();
 
    public interface IEvent
    {
        //微软推荐写法
        EventHandler myEventHandler { get; set; }
        event MyDelegate myDelegate;
        void Show();
    }

    public class MyClass : IEvent
    {
        public EventHandler myEventHandler { get; set; }
        public event MyDelegate myDelegate;
        public void Show()
        {
            if (myDelegate != null)
                myDelegate();
        }
    }
}

 

C#的事件

标签:

原文地址:http://www.cnblogs.com/lgxlsm/p/4772104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!