C# new [delegate] not necessary?

前端 未结 3 1770
傲寒
傲寒 2020-12-18 08:04

I\'ve been playing with HttpWebRequests lately, and in the tutorials they always do:

IAsyncResult result = request.BeginGetResponse(
  new Async         


        
3条回答
  •  再見小時候
    2020-12-18 08:43

    It's the same thing, mostly (there are a few overload rules to think about, although not in this simple example). But in previous versions of C#, there wasn't any delegate type inference. So the tutorial was either (a) written before delegate type inference was available, or (b) they wanted to be verbose for explanation purposes.

    Here's a summary of a few of the different ways you can take advantage of delegate type inferencing:

    // 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(); });
    

提交回复
热议问题