Skip to main content
 首页 » 编程设计

C# 闭包和访问外部变量

2024年02月23日15lvdongjie

我正在尝试通过调用使用以下内容:StaticClass.DeleteObject(null, key)。它没有像我预期的那样工作,并且 lambda 表达式中的代码抛出 NullReferenceException 因为 context 为 null,这是可以理解的。我尝试将 AmazonS3Operation 的上下文参数更改为 ref,但 ReSharper 随后警告“访问已修改的闭包。”

基本上,我只是想在该辅助方法中“注入(inject)”lambda 表达式,然后调用它,如果您了解我希望它如何工作的话。这可能吗?如果不可能,我能做些什么?

/// <exception cref="IOException"></exception> 
public static void DeleteObject(this AmazonS3Context context, string key) 
{ 
    AmazonS3Operation(context, () => context.Client.DeleteObject( 
        new DeleteObjectRequest().WithBucketName(context.CurrentBucket) 
            .WithKey(key))); 
} 
 
/// <exception cref="IOException"></exception> 
private static void AmazonS3Operation(AmazonS3Context context, Action operation) 
{ 
    var shouldDispose = false; 
    try 
    { 
        if (context == null) 
        { 
            context = new AmazonS3Context(); 
            shouldDispose = true; 
        } 
 
        operation(); 
    } 
    catch (AmazonS3Exception e) 
    { 
        throw new IOException(e.Message, e); 
    } 
    finally 
    { 
        if (shouldDispose) 
            context.Dispose(); 
    } 
} 

请您参考如下方法:

我会将上下文传递到操作中。将 Action 参数替换为 Action 参数。

        /// <exception cref="IOException"></exception> 
    public static void DeleteObject(this AmazonS3Context context, string key) 
    { 
        context = null; 
        AmazonS3Operation(context, ctx => ctx.Client.DeleteObject( 
            new DeleteObjectRequest().WithBucketName(ctx.CurrentBucket) 
                .WithKey(key))); 
    } 
 
    /// <exception cref="IOException"></exception> 
    private static void AmazonS3Operation(AmazonS3Context context, Action<AmazonS3Context> operation) 
    { 
        var shouldDispose = false; 
        try 
        { 
            if (context == null) 
            { 
                context = new AmazonS3Context(); 
                shouldDispose = true; 
            } 
 
            operation(context); 
        } 
        catch (AmazonS3Exception e) 
        { 
            throw new IOException(e.Message, e); 
        } 
        finally 
        { 
            if (shouldDispose) 
                context.Dispose(); 
        } 
    }