【发布时间】:2016-12-24 19:19:31
【问题描述】:
您好,这是 C# 语言如何处理 Com 互操作资源管理的示例。 orginal source:
Excel.Application app = null;
Excel.Workbooks books = null;
Excel.Workbook book = null;
Excel.Sheets sheets = null;
Excel.Worksheet sheet = null;
Excel.Range range = null;
try
{
app = new Excel.Application();
books = app.Workbooks;
book = books.Add();
sheets = book.Sheets;
sheet = sheets.Add();
range = sheet.Range["A1"];
range.Value = "Lorem Ipsum";
book.SaveAs(@"C:\Temp\ExcelBook" + DateTime.Now.Millisecond + ".xlsx");
book.Close();
app.Quit();
}
finally
{
if (range != null) Marshal.ReleaseComObject(range);
if (sheet != null) Marshal.ReleaseComObject(sheet);
if (sheets != null) Marshal.ReleaseComObject(sheets);
if (book != null) Marshal.ReleaseComObject(book);
if (books != null) Marshal.ReleaseComObject(books);
if (app != null) Marshal.ReleaseComObject(app);
}
我个人认为上面的代码是合理和必要的。但它不是功能或 F# 方式。我最终在嵌套 try...finally 和 try...with 的不同级别定义了所有这些 com 变量,因为必须在 try 块之前定义变量,所以清理代码存在于 finally 块和 with 块中。这是非常混乱的。
如何在 F# 中正确实现相同的功能?有点讽刺的是,互联网上有很多例子解释了如何使用 F# 和互操作来展示 F# 的力量。然而,他们都没有讨论如何管理 com 资源清理。
欢迎任何关于良好模式的建议。
【问题讨论】:
-
非常简短,因为我在手机上:使用 IDisposable 对象(如果 Com 没有实现 IDisposable,则使用包装器),并使用 F#
use表达式。它类似于let,只是它在对象超出范围时调用 Dispose()。
标签: c# f# com functional-programming excel-interop