C# 委托与事件实例说明(猫叫,老鼠逃,人醒)

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

namespace delegateEvent
{
    class callEventArgs : System.EventArgs
    {
        private string Name;
        public callEventArgs(string CName)
        {
            this.Name = CName;
        }
        public string name
        {
            get
            {
                return Name;
            }
            set
            {
                this.Name = value;
            }
        }
    }
    public delegate void CallEventHandler(object sender,callEventArgs e);
 class Cat
 {
        public event CallEventHandler Call;
        public virtual void OnCall(callEventArgs e)
        {
            if (Call != null)
            {
                Call(this, e);
            }
        }
        public void Calling(string CatName)
        {
            Console.WriteLine("猫大叫");
            OnCall(new callEventArgs(CatName));
        }
 }
    class Mouse
    {
        private string Name;
        public Mouse(string MName)
        {
            this.Name = MName;
        }
        public string mName
        {
            get
            {
                return Name;
            }
            set
            {
                this.Name = value;
            }
        }
        public void Response(object sender, callEventArgs e)
        {
            Console.WriteLine(Name+"四处逃跑");
        }
    }
    class Person
    {
        private string Name;
        public Person(string PName)
        {
            this.Name = PName;
        }
        public string pName
        {
            get
            {
                return Name;
            }
            set
            {
                this.Name = value;
            }
        }
        public void Response(object sender, callEventArgs e)
        {
            Console.WriteLine(Name + "醒了");
        }
    }
    class Relation
    {
        static void Main()
        {
            Cat cat = new Cat();
            Mouse mouse = new Mouse("kitty");
            Person men = new Person("Person");
            cat.Call+=new CallEventHandler(mouse.Response);
            cat.Call+=new CallEventHandler(men.Response);
            cat.Calling("cat");
        
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值