简体   繁体   中英

What is the exact meaning of delegate() method in C#?

I am pretty new in C# (I came from Java) and I am working on a SharePoint project.

I have the following doubt related to this method in my code:

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    lock (this)
    {
        try
        {
            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                DeleteExistingJob(JobName, parentWebApp);
            });
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

as you can see this code is executed into delegate() {...} "block":

SPSecurity.RunWithElevatedPrivileges(delegate ()
{
    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
    DeleteExistingJob(JobName, parentWebApp);
});

What exactly means this delegate() method?

Reading here: https://docs.microsoft.com/it-it/dotnet/csharp/language-reference/keywords/delegate

it seems to me that it somethings like a way to declare an "anonymous" method where the implementation of this method is the code into the {...} block.

Is this the correct interpretation or am I missing something?

In case it is correct what is the pourpose of this delegate() method? Why I am not declaring the code into a classic method? What is it exact pourpose?

As per the documentation you referred to, the delegate keyword is used for two purposes:

  • To declare a delegate type
  • To create an anonymous method which is converted into a delegate instance

Now you could write all the code in an anonymous method in a regular method and then use a method group conversion to create a delegate instance, but that can often be annoying - particularly if you want to use any local variables or parameters in the anonymous method.

So that's why you'd use an anonymous method - or in anything from C# 3 onwards, you're more likely to use a lambda expression instead.

Consider how you'd have to create the delegate in your example if you didn't use an anonymous method or lambda expression. You'd need to write something like this:

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    lock (this)
    {
        // Note: try/catch removed as it's pointless here, unless you're
        // *trying* to obscure the stack trace in case of an exception
        JobDeletionHelper helper = new JobDeletionHelper(properties);
        // Note that we're using a method group conversion here - we're not
        // invoking the method. We're creating a delegate which will invoke
        // the method when the delegate is invoked.
        SPSecurity.RunWithElevatedPrivileges(helper.DeleteJob);
    }
}
// We need this extra class because the properties parameter is *captured*
// by the anonymous method
class JobDeletionHelper
{
    private SPFeatureReceiverProperties properties;

    internal JobDeletionHelper(SPFeatureReceiverProperties properties)
    {
        this.properties = properties;
    }

    public void DeleteJob()
    {
        // This is the code that was within the anonymous method
        SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
        DeleteExistingJob(JobName, parentWebApp);
    }
}

If you're asking about the purpose of delegates themselves, that's a slightly bigger topic - but in a nutshell, it's the ability to represent executable code as an object, so it can be passed to other code to execute. (You can think of a delegate type as being like a single-method interface, if that's useful.)

it seems to me that it somethings like a way to declare an "anonymous" method where the implementation of this method is the code into the {...} block.

Yes, that is on point!

In case it is correct what is the pourpose of this delegate() method? Why I am not declaring the code into a classic method? What is it exact pourpose?

Since you mentioned that you came from Java you can think of passing a delegate(){ ... } as passing an anonymous class in java to some extent.

In Java, an anonymous class enables you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name . Use them if you need to use a local class only once .

For example, In Java prior to JDK8 you could do:

btn.setOnAction(new EventHandler<ActionEvent>() {  //<--- implementation
        @Override
        public void handle(ActionEvent event) {
             System.out.println("Hello World!");
        }
  });

or as of JDK8:

btn.setOnAction(e -> System.out.println("Hello World!"));

Likewise in C# delegate () {...} is allowing you to pass an implementation ie some behaviour on the fly.

It was common pattern a while back to use delegate () {...} but now you're most likely to use a lambda equivalent of () => { ... }


You may find these posts of interest:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM