C#中delegate()方法的确切含义是什么?

And*_*ili 1 c# delegates

我是C#的新手(我来自Java),我正在开发一个SharePoint项目.

我在代码中对此方法有以下疑问:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此代码执行到delegate(){...} "block":

SPSecurity.RunWithElevatedPrivileges(delegate ()
{
    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
    DeleteExistingJob(JobName, parentWebApp);
});
Run Code Online (Sandbox Code Playgroud)

这个delegate()方法的确切含义是什么?

在这里阅读:https://docs.microsoft.com/it-it/dotnet/csharp/language-reference/keywords/delegate

在我看来,它有点像一种声明"匿名"方法的方法,其中此方法的实现是{...}块中的代码.

这是正确的解释还是我错过了什么?

如果它是正确的,这个delegate()方法的pourpose是什么?为什么我没有将代码声明为经典方法?什么是精确的pourpose?

Jon*_*eet 5

根据您提到的文档,该delegate关键字用于两个目的:

  • 声明委托类型
  • 创建一个转换为委托实例的匿名方法

现在,您可以在常规方法中以匿名方法编写所有代码,然后使用方法组转换来创建委托实例,但这通常很烦人 - 特别是如果您想在匿名方法中使用任何局部变量或参数.

这就是为什么你要使用匿名方法 - 或者在C#3以后的任何东西中,你更可能使用lambda表达式.

如果您没有使用匿名方法或lambda表达式,请考虑如何在示例中创建委托.你需要写这样的东西:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你问的是代表自己的目的,这是一个稍微大一点的话题 - 但简而言之,它是将可执行代码表示为对象的能力,因此可以将其传递给其他代码来执行.(您可以将委托类型视为单方法接口,如果它有用.)