首页 > 解决方案 > 在 C# 中执行

问题描述

我正在尝试实现 Kent Beck 的 Smalltalk Best Practice Patterns 中描述的Execute Around模式。可以在此处找到 Java 示例。

基本上,我在执行各种操作时反复打开和关闭 pdf 文档,例如,

public void Parse()
{
    // Open the document
    PdfLoadedDocument loadedDocument = new PdfLoadedDocument("plan.pdf");

    List<string> annotations = Build(loadedDocument);

    // Close the document
    loadedDocument.Save();
    loadedDocument.Close();
}

我想将文档的打开和关闭移动到一个集中的地方,因为我有几十个类似的方法。所有这些方法都打开文档,执行操作,关闭文档,很容易忘记关闭文档。

这是我尝试过的:

public void BuildAnnotations()
{
    List<string> annotations = null;

    ExecuteAction("plan.pdf", (PdfLoadedDocument loadedDocument) =>
    {
        annotations = Build(loadedDocument);
    });
}

private void ExecuteAction(string path, Action<PdfLoadedDocument> perform)
{
    PdfLoadedDocument loadedDocument = new PdfLoadedDocument(path);

    try
    {
        perform(loadedDocument);
    }
    catch(Exception e)
    {
        Console.WriteLine($"An error occured. {e}");
    }

    loadedDocument.Save();
    loadedDocument.Close();
}

我的问题是,将 lambda 传递给 Action 代表是个好主意吗?我对委托、动作和 lambdas 不太熟悉(除了在 linq 查询中使用它们)。还有其他更好的选择吗?

标签: c#.netdesign-patternslambdadelegates

解决方案


你有没有考虑实现IDisposable接口,所以以后你可以使用using关键字,例如:

using (PdfLoadedDocument loadedDocument = new PdfLoadedDocument(path))
{
    List<string> annotations = Build(loadedDocument);
}

public class PdfLoadedDocument : IDisposable
{
    public void Close()
    {

    }

    public void Save()
    {

    }

    public void Dispose()
    {
        Save();
        Close();
    }
}

推荐阅读