如果我有一个 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/