C#事件代理简单例子

 

事件与代理是比较难理解的部分,本人从中学习中写出的比较好理解的例子,C#中的delegate和C++中的函数指针基本是一回事,C#正是以delegate的形式实现了函数指针。不同的地方在于C#中delegate是类型安全的。

例一:

namespace DelegateTest
{
    public delegate void MyDelegate();
    class Test
    {
        static void Main(string[] args)
        {
            ChangedEvent chanevent = new ChangedEvent();
            EventListener eventlis = new EventListener(chanevent);
            chanevent.OnChanged();

          
           
            Console.Read();
        }
    }
   //定义一个包含事件成员的类,当发生变化时,就会触发事件
    public class ChangedEvent
    {
       public event MyDelegate Changed;
       public void OnChanged()
        {
            if (Changed != null)
                Console.WriteLine("触发事件:");

                Changed();
        }
       
    }
    

    //创建包含处理方法的类
    class EventListener
    {
        //用以保存从构造涵数的参数传递来的对象,主要是为了以后解除事件绑定
       // private ChangedEvent CE;

        public EventListener(ChangedEvent ce)
        {
           // CE = ce;
            ce.Changed += new MyDelegate(DispMethod);
        }
        private void DispMethod()
        {
            Console.WriteLine("This is called when the event fires.");
       
        }
      
    }
}

例二:

namespace Delegate2
{
 
    public delegate void MyDelegate();
    class Test
    {
      
        static void Main(string[] args)
        {
            ChangedEvent chanevent = new ChangedEvent();
            A a=new A();
            chanevent.Changed += new MyDelegate(a.DispMethod);
            chanevent.OnChanged();

          
           
            Console.Read();
        }
    }
    class A
    {

       public void DispMethod()
        {
            Console.WriteLine("This is called when the event fires.");

        }
    }
   
   //定义一个包含事件成员的类,当发生变化时,就会触发事件
    public class ChangedEvent
    {
        //public delegate void MyDelegate();
       
        public event MyDelegate Changed;
        public void OnChanged()
        {
            if (Changed != null)
            {
                Console.WriteLine("触发事件:");

                Changed();
            }
        }

例三:有参数形的Delegate
       

 namespace ConsoleApplication1
{
//定义委托
public delegate bool CompareInt(int a, int b);
public class MyCompare
{
public static bool ShowResult(int x , int y)
{
bool index = x > y ? true : false;
return index;
}

}
class Program
{

static void Main(string[] args)
{
CompareInt   myDelegate = new CompareInt(MyCompare.ShowResult);
int a = 20;
int b = 15;
bool whoBigger = myDelegate(a, b);
Console.WriteLine(" a > b ?: " + whoBigger );
Console.Read();
}
}


 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值