Delegate Demo

孤人 提交于 2019-11-29 12:47:29

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

 

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();
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!