对于C#中委托和事件的理解

委托与事件的结合可以更好的降低对象之间的“耦合性”,取生活中的一个场景,孩子饿了,要哭,爸爸妈妈听到哭声都会赶过来。如果按照常规的编程方法,我们可能要在Child类里边实现一个方法来通知爸爸和妈妈,假设有一天这家聚会,爷爷奶奶,姥姥姥爷,姑姑婶婶全过来了,那么孩子必须要通知增加的这些人,我们就不得不修改Child类里的这个方法。
而事实上我们可以这样考虑,将对孩子哭这一事件关心的一类人抽象出来,爷爷奶奶,姥姥姥爷,姑姑婶婶都从该类派生,他们有一个公共的代理,只要他们讲自己的行为“注册”到这个代理,孩子一哭,所有被注册进去的事件就会形成一个事件的链表然后顺次执行。在这种模式下Child类和Observer类的派生类之间的耦合性大大降低了,我们不需要对Child类的方法进行任何的修改而只需要讲Observer类的派生类的各个实例对象对“孩子哭”这一事件的响应注册到“孩子哭”中就可以了。

using System;
namespace EventTest
{
    
public delegate void EventHandle(object sender, EventArgs e);
    
class Entry
    
{
        
public static void Main()
        
{
            Woman woman 
= new Woman();
            Man man 
= new Man();
            Child child 
= new Child();
            child.call 
+= new EventHandle(woman.observer_call);
            child.call 
+= new EventHandle(man.observer_call);
            child.observer_call(
nullnull);
        }

    }


    
abstract class observer
    
{
        
public event EventHandle call;
        
public void Subto(observer ob)
        
{
            
this.call += new EventHandle(ob.observer_call);
        
        }


        
abstract public void observer_call(object sender, EventArgs e);

        
public void Shout()
        
{
            
if (call != null)
            
{
                call(
thisnull);
            }

        }

    }

    
class Woman : observer
    
{
        
        
public override void observer_call(object sender, EventArgs e)
        
{
            
//throw new Exception("The method or operation is not implemented.");
            Console.WriteLine("Woman : Oh Baby, mom is coming!");
            Shout();
        }

    }

    
class Man : observer
    
{
        
public override void observer_call(object sender, EventArgs e)
        
{
            
//throw new Exception("The method or operation is not implemented.");
            Console.WriteLine("Man : Oh Baby, papa is coming!");
            Shout();
            
        }

        
    }

    
class Child : observer
    
{
        
public override void observer_call(object sender, EventArgs e)
        
{
            
//throw new Exception("The method or operation is not implemented.");
            Console.WriteLine("Child : Where are my parents? I'm hungry!");
            Shout();
        }

    }

}


在第4行中定义了一个委托,它的作用是将被委托的函数以参数形式“传递”给事件,从而构成一个事件的链表,其作用与函数指针相似。
observer类里的Subto()函数负责将某一个对象的方法注册到该类的实例中。而call(this, null)则在该点将委托所指向的实例方法执行。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章