2011-11-09 39 views
0

在我看來,代表似乎是要學習的具有挑戰性的概念之一。代表的實際實施

從我的理解來看,delegate是一個方法指針,它指向運行時的特定方法。

我是代表的例子之一是在文件處理期間,在調用方法並在方法調用後釋放文件資源之前,可以執行一些文件操作。在此使用委託可改善可重用性。

我的問題是,你能否啓發我日常編程的代表的其他實際用途?

謝謝提前!

+0

http://msdn.microsoft.com/en-us/library/ms173171(v=VS.100).aspx – Lloyd

+0

三江源的支持。 – Karthik

回答

0

委託在與自定義事件處理程序一起使用時很有用。

代表是您可以在 運行時爲您的調用方法定義的規則。

E.g public delegate void NameIndicator(string name);

您可以將方法綁定到委託並將其註冊到事件。

請看下面的例子。

public delegate void NameIndicator(string name); 

class Program 
{ 
    static void Main(string[] args) 
    { 
     //Create the instance of the class 
     Car car = new Car("Audi"); 
     //Register the event with the corresponding method using the delegate 
     car.Name += new NameIndicator(Name); 
     //Call the start to invoke the Name method below at runtime. 
     car.Start(); 
     Console.Read(); 
    } 

    /// <summary> 
    /// The method that can subscribe the event of the defined class. 
    /// </summary> 
    /// <param name="name">Name assigned from the caller.</param> 
    private static void Name(string name) 
    { 
     Console.WriteLine(name); 
    } 

} 

public class Car 
{ 
    //Event for the car class. 
    public event NameIndicator Name; 
    string name; 

    public Car(string nameParam) 
    { 
     name = nameParam; 
    } 

    //Invoke the event when the start method is called. 
    public virtual void Start() 
    { 
     Name(name); 
    } 
} 
3

那麼,總的來說,代表最主要的用途是通過事件及其處理程序。如果你認識到這一點,由於你的措辭你的問題的辦法,我也說不上來,但每次你寫

someObj.SomeEvent += SomeMethod; 

您正在使用的代表,具體而言,SomeMethod是由委託實例包裹。

+0

謝謝先生。這是非常豐富的。我期待着你的帖子。 – Karthik

0

您還將使用委託與線程:

//Anynymous delegate 
new Thread(delegate() 
{ 
     Console.WriteLine("Hello world form Thread"); 
}); 

//Lambda expression 
new Thread(() => 
{ 
     Console.WriteLine("Hello world form Thread"); 
}); 

,看一下lambda表達式,它功能強大:Lambda expression

+0

感謝你,我對代表使用線程的意識有所增加,因爲我沒有意識到這一點。 我期待着您的帖子。 – Karthik