對於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)則在該點將委託所指向的實例方法執行。
 

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