尝试/最后阻止vs调用处置? [英] Try/Finally block vs calling dispose?
本文介绍了尝试/最后阻止vs调用处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这两个代码示例之间是否有区别,如果没有,为什么存在使用
?
Is there any difference between these two code samples and if not, why does using
exist?
StreamWriter writer;
try {
writer = new StreamWriter(...)
writer.blahblah();
} finally {
writer.Dispose();
}
vs:
using (Streamwriter writer = new Streamwriter(...)) {
writer.blahblah
}
我的意思是,在第二个示例中,无论如何,您实际上都应该将其放在try块中,因此添加finally块确实不会花费太多精力。我知道整个内容可能包含在更大的try块中,但是,对我来说似乎是多余的。
I mean in the second example you really should be putting it in a try block anyway so adding the finally block really doesn't use much more effort. I get that the entire thing might be encompassed in a bigger try block but yeah, just seems superfluous to me.
推荐答案
有关于您的代码一些问题。 从不这样写(改为使用),而这就是为什么:
There're some issues with your code. Never write like this (put using instead), and that's why:
StreamWriter writer;
try {
// What if you failed here to create StreamWriter?
// E.g. you haven't got permissions, the path is wrong etc.
// In this case "writer" will point to trash and
// The "finally" section will be executed
writer = new StreamWriter(...)
writer.blahblah();
} finally {
// If you failed to execute the StreamWriter's constructor
// "writer" points to trash and you'll probably crash with Access Violation
// Moreover, this Access Violation will be an unstable error!
writer.Dispose();
}
当您像这样使用时
using (StreamWriter writer = new StreamWriter(...)) {
writer.blahblah();
}
等于代码
StreamWriter writer = null; // <- pay attention to the assignment
try {
writer = new StreamWriter(...)
writer.blahblah();
}
finally {
if (!Object.ReferenceEquals(null, writer)) // <- ... And to the check
writer.Dispose();
}
这篇关于尝试/最后阻止vs调用处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文