何时使用Using语句

发布于 2024-10-24 18:37:34 字数 616 浏览 1 评论 0原文

我想我在这里使用的Using语句可能是错误的。写这个的更好方法是什么?

Dim x As New Serialization.XmlSerializer( ... )
Using file As New FileStream(myFile, FileMode.Create)
   Using writer As XmlWriter = XmlTextWriter.Create(file)
      x.Serialize(writer, myCollection)
   End Using
End Using

我读到您只能在具有 .Dispose() (即实现 IDisposable)的对象上使用 using 块,这就是我的原因认为不应该在“writer”上使用Using,而应该在最后使用writer.Close()。但是“file”同时具有 .Dispose().Close(),那么我该使用哪一个呢? using 还是 file.Close()

注意:我使用 XmlWriter 因为我可以自定义输出。不过,我删除了这里的设置。

I think I may be using the Using statement wrong here. What would be a better way of writing this?

Dim x As New Serialization.XmlSerializer( ... )
Using file As New FileStream(myFile, FileMode.Create)
   Using writer As XmlWriter = XmlTextWriter.Create(file)
      x.Serialize(writer, myCollection)
   End Using
End Using

I've read that you're only supposed to use a using block on objects that have a .Dispose() (i.e. implements IDisposable), which is why I'm thinking there shouldn't be a Using on "writer", but instead a writer.Close() at the end. But "file" has both a .Dispose() and a .Close(), so which do I use? The using or file.Close()?

Note: I'm using an XmlWriter because I can customize the output. I removed the settings here, though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

被翻牌 2024-10-31 18:37:34

FileStreamXmlWriter 都实现了 IDisposable - 代码是正确的。实际上,如果错误的话,编译器可能不会让你这样做。如果没有公共 .Dispose(),那么它必须使用显式接口实现 - 但这不会改变您调用 .Dispose 的责任()。出于兴趣,在 C# 中,您可以避免不断增加的嵌套/缩进,即,

using(...a...)
using(...b...)
using(...c...)
{
   ...
}

但从根本上讲,您当前的代码是正确的。

Both FileStream and XmlWriter implement IDisposable - the code is correct. Actually the compiler probably wouldn't let you do this if it was wrong. If there isn't a public .Dispose(), then it must be using explicit interface implementation - but that doesn't change your responsibility for calling .Dispose(). For interest, in C# you can avoid the ever-increasing nesting/indenting, i.e.

using(...a...)
using(...b...)
using(...c...)
{
   ...
}

but fundamentally your current code is correct.

坚持沉默 2024-10-31 18:37:34

这确实令人困惑,并且一直是很多争论的话题。这是 Dispose() 方法的实现:

Public Sub Dispose()
    Me.Close
End Sub

换句话说,调用 Dispose() 与调用 Close() 执行的操作完全相同。您肯定想利用这里的Using 语句。

This is indeed confusing and has been the subject of much debate. This is the implementation of the Dispose() method:

Public Sub Dispose()
    Me.Close
End Sub

In other words, calling Dispose() does the exact same thing as calling Close(). You definitely want to take advantage of the Using statement here.

淡忘如思 2024-10-31 18:37:34

是的,.Close .Dispose 问题有点不幸。

不过,它是(曾经是?)官方的 MS 指南。 Close 方法称为域特定别名

就像 Alias 这个词所暗示的那样,您可能会认为它们的作用完全相同。通常 Close 只会调用 Dispose。

Using ... End using 块将仅使用 IDisposable(具有 .Dispose)的引用进行编译


一般建议:

  • 当类具有 .Dispose 时,使用 Using block
  • Using 只是 Try ... Final 的简写,您可以依靠它。但是
  • 不要创造性地尝试组合或节省多个块
  • 当嵌套深入(> 3..5)时,请考虑出一个额外的方法。

Yes, the .Close and .Dispose issue is a bit unfortunate.

It is (was?) an official MS guideline though. The Close method is called a Domain Specific Alias.

And like the word Alias suggests, you may assume that they do exactly the same. Usually Close will just call Dispose.

The Using ... End Using block will only compile with a reference that is IDisposable (has .Dispose)


General advice:

  • When a Class has a .Dispose, use aUsing block
  • Using is just short-hand for Try ... Finally and you can fall back on that. But
  • Don't get creative trying to combine or economize multiple blocks
  • When the nesting gets to deep (> 3..5), factor out an extra method.
挖个坑埋了你 2024-10-31 18:37:34

你的代码看起来是正确的。请注意,如果您尝试在不支持 IDispose 的数据类型上使用 using,您将收到编译时错误。

Your code looks correct. Note that you will get a compile-time error if you attempt to use using on a data type that does not support IDispose.

因为看清所以看轻 2024-10-31 18:37:34

我倾向于两者都做,但这可能是因为我有点守旧。如果我打开了一个文件(你也有),我会明确关闭它。 Dispose 方法是否完全关闭取决于对象的实现,而不取决于客户端。但是,由于该对象仍然实现 IDisposable,因此您仍然需要调用它。

I'd tend to do both, but that could be because I'm a bit old fashioned. If I've opened a file (which you have), I'll explicitly close it. Whether or not the Dispose method does a clean close is up to the implementation of the object, not up to the client. But, as the object still implements IDisposable you still need to call it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文