首页 > 代码库 > 使用委托中介租房理解委托与事件

使用委托中介租房理解委托与事件

委托和事件,.Net Framework中的应用非常广泛,然而,较好的理解委托和事件对很多接触C#时间不长的人来说并不容易。它们就像一道门槛儿,跨过去的,觉得太容易了,而没有过去的人每次见到委托事件就觉得心慌慌,浑身不自在。

我个人还是比较喜欢用面向对象的编程思想去理解逻辑程序,理解编程。下面就用委托中介公司租房子的示例理解使用委托流程:

1.定义委托和委托对象——租房人想要租房,但是没有房源,于是委托中介找房子;
2.编写要委托的方法——租房中介有房源,可以找到房子;
3.将要委托的方法传递给委托对象——租房人来到租房中介公司,把租房委托传达给中介公司;
4.使用委托调用委托方法——中介公司开始找房子;

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 使用委托模拟租房{    class Program    {        static void Main(string[] args)        {            Customer customer = new Customer("王天", RoomType.OneBedRoom, 1000);            Agency agency = new Agency("美家");            Room room1 = new Room(RoomType.OneBedRoom,1000);            Room room2 = new Room(RoomType.TwoBedRoom, 3000);            agency.roomList.Add(room1);            agency.roomList.Add(room2);            customer.findRoom = agency.FindRoom;            customer.FindRoom();        }    }    /// <summary>    /// 房间类型枚举    /// </summary>    public enum RoomType    {        OneBedRoom, TwoBedRoom, ThreeBenRoom    }    /// <summary>    /// 房间类    /// </summary>    class Room    {        public Room(RoomType type,int price)        {            this.RoomType = type;            this.Price = price;        }        public RoomType RoomType { get; set; }        public int Price { get; set; }    }    /// <summary>    /// 客户类    /// </summary>    class Customer    {        public Customer(string name, RoomType type, int price)        {            this.CusName = name;            this.wantPrice = price;        }        public string CusName { get; set; }        public RoomType wantRoomType { get; set; }        public int wantPrice { get; set; }                public delegate void LetAgencyToFindRoom(RoomType roomType, int roomPrice);        public LetAgencyToFindRoom findRoom;        //让中介找房子的方法        public void FindRoom()        {            Console.WriteLine(CusName + "说:我要找一套" + wantRoomType + "的房子,价格不高于" + wantPrice);            findRoom(wantRoomType, wantPrice);        }    }    /// <summary>    /// 中介类    /// </summary>    class Agency    {        public Agency(string name){        }        public string AgencyName { get; set; }        public List<Room> roomList = new List<Room>();        public void FindRoom(RoomType type, int roomPrice)        {            Console.WriteLine(AgencyName + "中介开始找房子");            Room room = null;            foreach (Room r in roomList)            {                if (r.RoomType == type && r.Price <= roomPrice)                {                    room = r;                }            }            if (room != null)            {                Console.WriteLine("找到一套:类型:" + room.RoomType + "价格:" + roomPrice);            }            else            {                Console.WriteLine("没有找到适合您的房子!");            }            Console.ReadLine();        }    }}

 

使用委托中介租房理解委托与事件