2015-11-07 23 views
3

委託的具體用法按照MSDN documentation,它說,它是爲以下目的除了給別人這是可以理解的有用:瞭解C#

  1. 類可能需要多於一個的方法實現。
  2. 需要封裝一個靜態方法。

    有人可以幫我理解這些用法的例子嗎?

+1

我沒有看到你鏈接到的文檔中的任何一條語句。 –

+0

它在章節何時使用代表而不是接口(C#編程指南https://msdn.microsoft.com/en-us/library/ms173173.aspx – venerik

+0

更正鏈接。謝謝 – Learner

回答

3

代表是一種參照方法,可以繞過作爲對象。

想象一下,有一個方法可以讓調用者提供自己的邏輯部分,這是多麼有用。每個調用者都可以擁有自己的方法,爲其方法創建委託(引用),並將其作爲參數傳遞給方法。只要主方法知道傳入的參數(如果有),它就可以通過引用(委託)調用該方法。

這裏有一個簡單的例子,具體的使用#1你的問題:

void RemoveItem(string item, Action preRemoveLogic) 
{ 
    preRemoveLogic(); //we don't know what method this actually points to, 
        //but we can still call it. 
    //remove the item 
} 

void MyCustomLogic() 
{ 
    //do something cool 
} 

/* snip */ 
RemoveItem("the item", new Action(MyCustomLogic)); 
//I can pass a reference to a method! Neat! 

Delegates are also very important for making events work in .NET