c# - 当 c# .net using block 失败时会发生什么?

标签 c# .net block using

如果我有一个 using block ,我在其中创建了一个对象(例如 FileStream 对象),而该对象创建失败(返回 null、抛出异常等), block 中的代码是否仍然执行?

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
    // do stuff with fs here
}
// do more stuff after

如果 FileStream 构造函数返回 null(如果 FileStream 构造函数总是返回一个有效对象,我们只是为了论证说它可以返回 null),里面的代码会执行吗?或者它会跳过“在这里用 fs 做事”代码吗?

最佳答案

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
{
    // do stuff with fs here
}
// do more stuff after

相当于:

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
try
{
    // do stuff with fs here
}
finally
{
    if (fs != null)
    {
        ((IDisposable)fs).Dispose();
    }
}
// do more stuff after

所以回答你的问题:

If the FileStream constructor were to return null (if the FileStream constructor always returns a valid object, let's just say for sake of argument that it is possible to return null), would the code inside execute?

是的,会的。

很明显,熟悉 C# 规范的每个人都知道构造函数(无论是哪种类型)永远不会返回 null,这让您的问题有点不切实际。

关于c# - 当 c# .net using block 失败时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11832249/

相关文章:

c# - 如何创建返回对象属性并具有此属性名称的 lambda 表达式?

objective-c - Objective-C : Anonymous Blocks, 为什么以及何时?

mysql - MySQL 上的 Firebird 执行 block

c# - WPF - 交换 ContentControl(重新链接元素???)

c# - 我应该如何管理/声明开源 C# 项目之间的依赖关系?

.net - 如何手动创建一个 mdf 文件供 localdb 使用?

c# - 如何从linq中的子表中选择列

ruby - Ruby中 block 的使用顺序是什么

c# - ASP.NET Gridview ButtonField onclick 触发包含行的 onclick 事件

c# - 在 C# 2.0 中将 Dictionary<string,List<foo>> 转换为 List<foo>