2009-12-27 50 views
5

我一直在玩HttpWebRequest小號近來,在教程他們總是這樣:C#新[委託]沒有必要?

IAsyncResult result = request.BeginGetResponse(
    new AsyncCallback(UpdateItem),state); 

new AsyncCallback似乎並沒有被necesary。如果UpdateItem有正確的簽名,那麼似乎沒有問題。那麼人們爲什麼要包括它?它是否做任何事情?

+0

我通常不會使用'new DelegateType(...)',也想知道這是否會做任何事情。 MSDN在這裏沒有真正談到它:http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx – 2009-12-27 07:34:26

+0

可能的重複[C#:'+ = anEvent'和'+ = new EventHandler(anEvent)'](http://stackoverflow.com/questions/550703/c-difference-between-anevent-and-new-eventhandleranevent) – nawfal 2014-07-06 20:16:24

回答

12

這是一樣的事情,主要是(有一些重載規則要考慮,雖然不是在這個簡單的例子中)。但在以前的C#版本中,並沒有任何委託類型推斷。所以教程要麼是(a)在委託類型推斷可用之前編寫的,要麼是(b)他們想要詳細解釋的目的。

這裏有幾個你可以採取委託類型推理的優勢不同方式的總結:

// Old-school style. 
Chef(new CookingInstructions(MakeThreeCourseMeal)); 

// Explicitly make an anonymous delegate. 
Chef(delegate { MakeThreeCourseMeal }); 

// Implicitly make an anonymous delegate. 
Chef(MakeThreeCourseMeal); 

// Lambda. 
Chef(() => MakeThreeCourseMeal()); 

// Lambda with explicit block. 
Chef(() => { AssembleIngredients(); MakeThreeCourseMeal(); AnnounceDinnerServed(); }); 
2

AsyncCallback只是在C#中的委託,在您通過方法的名稱本身只要簽名,編譯器相匹配通常會取代你的代碼,它只是快捷方式被聲明爲

public delegate void AsyncCallback(IAsyncResult ar); 

您可以使用Reflector簡單檢查。如果你有這個例子。

request.BeginGetResponse(TestMethod, null); 

static void (IAsyncResult r) 
     { 
      //do something 
     } 

編譯後的代碼實際上看起來像這樣。

request.BeginGetResponse(new AsyncCallback(Test), null); 
2

爲了完整起見,這個C#1.2之間變化(與.NET 1.1)和C#2.0(帶。 NET 2.0)。所以從2.0開始,在大多數情況下確實可以省略new SomeDelegateType(...)。奇怪的是,工具並沒有改變,所以在IDE中,如果您鍵入someObj.SomeEvent += IDE將建議(通過選項卡選項卡)完整版本包括委託類型。

相關問題