c# - 在 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 查询中使用它们)。还有其他更好的选择吗?
解决方案
你有没有考虑实现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();
}
}
推荐阅读
- pervasive - Btrieve 文件只显示部分数据
- karate - 空手道是否支持 WebSocket 延续帧?
- java - 在这种情况下如何扩展自定义布局并编辑您的视图?
- laravel - 在laravel 6.0中计算各种列的元素
- vue.js - 在 vuejs 中将选定对象显示为字符串
- swift - 在 UITableView 中编辑时滑动删除
- python - 有没有办法只用ID找出公会名称?
- javascript - 提交按钮在模式弹出中不起作用,但单击按钮正在工作
- typescript - 使用 Vue CLI 安装 TypeScript 会返回 *找不到模块 'eslint-plugin-@typescript-eslint'*
- firebase - 解析服务器中的推送通知