博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Delegate Demo

Posted on 2008-11-27 16:10  功夫熊猫  阅读(219)  评论(0)    收藏  举报

//注:此例为完整实例.

 

using System;

using System.Collections.Generic;
using System.Text;

namespace ConsoleApplications
{
    public delegate void Counts(object sender, AreaEventArgs e);

    public class Core
    {
        public event Counts coArea;

        public void CountArea(int length, int width)
        {
            AreaEventArgs e = new AreaEventArgs();
            e.Length = length;
            e.Width = width;
            if (coArea != null)
            {
                coArea(this, e);
            }
        }
    }

  

    public class AreaEventArgs : EventArgs
    {
        private int _width;

        public int Width
        {
            get { return _width; }
            set { _width = value; }
        }
        private int _length;

        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }
    }

    public class Opea

    {

  //计算长方形面积

      public void rectangleArea(object sender, ConsoleApplications.AreaEventArgs e)

        {
            Console.WriteLine("The Rectangle Area is {0} cm2", e.Length * e.Width);
        }
    }

    public class DelegateDemo
    {
        public static void Main(string[] args)
        {
            Console.Write("Length:");
            string length = Console.ReadLine();
            Console.Write("Width:");
            string width = Console.ReadLine();
            int len = Convert.ToInt32(length);
            int wi = Convert.ToInt32(width);

            Core core = new Core();
            Opea opea = new Opea();
            core.coArea += new Counts(opea.rectangleArea);
            core.CountArea(len, wi);
            core.coArea -= new Counts(opea.rectangleArea);
            core.CountArea(3, 2);
            Console.ReadLine();
        }
    }
}