How to use delegates in correct way / Understanding delegates

后端 未结 3 1674
日久生厌
日久生厌 2020-12-18 06:07

use - C# (.Net Framework 4.5, Visual Studio 2012)

I try to understand such theme like Delegate, and currently I have few points, that must be clarified for me. I fo

3条回答
  •  情深已故
    2020-12-18 06:46

    Delegates in c# are a little bit like a replacement for function pointers in C++. There are plenty of usages for them. You can use them to:

    1. Crate an inline implementation for an event.
    2. Pass a callback to a function.
    3. Create a array of "functions" you can call in a loop.

    From my experience the first usage is the most common.

    Button.Click += delegate(object sender, EventArgs args)  => {/*you do something here*/};
    

    Which can be simplified by a lamba expression:

    Button.Click += (sender, args) => {/*you do something here*/};
    

    You provide some behavior to a button click not having to create a separate method for it.

    Regarding to the second part of your question, I usually put delegates declarations in separate files.

提交回复
热议问题