C# new [delegate] not necessary?

2019-01-25 18:17发布

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

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

But new AsyncCallback doesn't seem to be necesary. If UpdateItem has the right signature, then there doesn't seem to be a problem. So why do people include it? Does it do anything at all?

标签: c# delegates
3条回答
可以哭但决不认输i
2楼-- · 2019-01-25 18:37

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(); });
查看更多
爷的心禁止访问
3楼-- · 2019-01-25 18:44

AsyncCallback is just a delegate in C#, it is declared as

public delegate void AsyncCallback(IAsyncResult ar);

When you pass the method name itself as long as the signature matches the compiler will usually substitute the code for you, its just shortcut.

You can simply check this using Reflector. If you have this for example.

request.BeginGetResponse(TestMethod, null);

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

The compiled code will actually look like this.

   request.BeginGetResponse(new AsyncCallback(Test), null);
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-25 18:45

For completeness, this changes between C# 1.2 (with .NET 1.1) and C# 2.0 (with .NET 2.0). So from 2.0 onwards you can indeed omit the new SomeDelegateType(...) in most scenarios. Oddly, the tooling hasn't changed, so in the IDE if you type someObj.SomeEvent += the IDE will suggest (via tab tab) the full version including delegate type.

查看更多
登录 后发表回答