The application of generic delegate in project

Source: Internet
Author: User

Sentiment: The generic delegate basically belongs to a little understanding, but never really used in the project, sometimes feel that there is no suitable scene application, but read the article Artech brother, I understand that the original generic delegate can really do a lot of things, and the effect is often not used by the delegate to achieve.

action<t> Generic delegate: Encapsulates a method that takes only one parameter and does not return a value. You can use this delegate to pass a method as a parameter without explicitly declaring a custom delegate. The method must correspond to the method signature defined by this delegate. That is, the encapsulated method must have a parameter passed to it by value and cannot return a value. Of course, a generic delegate can support only one parameter, and it supports up to four parameters.

A generic delegate is compared to an example of a direct display declaration custom delegate:

1: Display declaration custom delegate:

delegate void DisplayMessage(string message);
public class TestCustomDelegate
{
    public static void Main()
    {
       DisplayMessage messageTarget;
       messageTarget = ShowWindowsMessage;
       messageTarget("Hello, World!");
    }
    private static void ShowWindowsMessage(string message)
    {
       MessageBox.Show(message);
    }
}

2:action<t> usage. It is obvious that the code is concise compared to the custom delegate.

public class TestAction1
{
    public static void Main()
    {
       Action<string> messageTarget;
      messageTarget = ShowWindowsMessage;
       messageTarget("Hello, World!");
    }
    private static void ShowWindowsMessage(string message)
    {
       MessageBox.Show(message);
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.