C# 如何在没有布尔值的情况下执行最后尝试捕获以释放资源
本文关键字:最后 释放资源 执行 情况下 布尔值 | 更新日期: 2023-09-27 17:56:14
我正在尝试执行一个 try-catch-final,以便如果成功创建 mainLog,但之后抛出异常,它将正确处理。但是,如果未成功创建 mainLog 并且存在 mainLog.Dipose()
方法调用,则会有另一个异常。通常,我会做一个 if 语句,但DocX.Create()
不返回布尔值,所以我不确定该怎么做。谢谢。
public static string Check_If_Main_Log_Exists_Silent()
{
DocX mainLog;
string fileName = DateTime.Now.ToString("MM-dd-yy") + ".docx";
string filePath = @"D:'Data'Main_Logs'";
string totalFilePath = filePath + fileName;
if (File.Exists(totalFilePath))
{
return totalFilePath;
}
else if (Directory.Exists(filePath))
{
try
{
mainLog = DocX.Create(totalFilePath);
mainLog.Save();
mainLog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("The directory exists but the log does not exist and could not be created. " + ex.Message, "Log file error");
return null;
}
}
else
{
try
{
mainLog = DocX.Create(totalFilePath);
mainLog.Save();
mainLog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("The directory and log does not exist and could not be created. " + ex.Message, "Log file error");
return null;
}
finally
{
if(mainLog)
}
}
}
添加 using 语句将仅在代码块末尾为 null 时才调用 dispose。它是那些方便的句法糖之一。
在一般情况下,默认情况下将mainLog
设置为 null
,并且仅在该方法不为 null 时才调用该方法。使用 C# 6,您可以使用方便的窗体:
mainLog?.Dispose();
对于旧版本,一个简单的if:
if (mainLog != null)
mainLog.Dispose();
如果对象实现了IDisposable
接口,那么使用 using
是最简单的方法,如 Gaspa79 的答案所示。