变量作用域和“使用” .NET 中的语句

发布于 2024-10-11 12:56:48 字数 301 浏览 7 评论 0原文

如果变量位于类级别(即 private MyDataAccessClass _dataAccess;),它可以用作该类方法中 using 语句的一部分以正确处理它吗?

使用它是否明智方法,或者最好始终使用 using 语句声明新变量(即 using (MyDataAccessClass dataAccess = new MyDataAccessClass()) 而不是 using ( _dataAccess = new MyDataAccessClass()))?

If a variable is at class level (ie, private MyDataAccessClass _dataAccess;, can it be used as part of a using statement within the methods of that class to dispose of it correctly?

Is it wise to use this method, or is it better to always declare a new variable with a using statement (ie, using (MyDataAccessClass dataAccess = new MyDataAccessClass()) instead of using (_dataAccess = new MyDataAccessClass()))?

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

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

发布评论

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

评论(3

一萌ing 2024-10-18 12:56:48

来自 MSDN

您可以实例化资源
对象,然后将变量传递给
using 语句,但这不是
最佳实践。在这种情况下,
控制后对象仍保留在范围内
留下 using 块,即使它
可能无法再访问
其非托管资源。在其他方面
话,它将不再完全
已初始化。如果您尝试使用
using 块之外的对象,您
导致异常的风险
抛出。正因如此,
通常更好地实例化
using 语句中的对象和
将其范围限制为 using 块。

因此,从技术上讲,它会起作用,因为它将按照设计进行编译、运行和执行。但这可能不是一个好主意,并且不会产生非常直观的代码。

From MSDN:

You can instantiate the resource
object and then pass the variable to
the using statement, but this is not a
best practice. In this case, the
object remains in scope after control
leaves the using block even though it
will probably no longer have access to
its unmanaged resources. In other
words, it will no longer be fully
initialized. If you try to use the
object outside the using block, you
risk causing an exception to be
thrown. For this reason, it is
generally better to instantiate the
object in the using statement and
limit its scope to the using block.

So technically it'll work, in that it will compile and run and perform as designed. But it's probably not a good idea and won't make for very intuitive code.

缘字诀 2024-10-18 12:56:48

我认为这并不重要,但我会使用局部变量而不是类级别变量,因为它减少了与其他类方法的耦合。

I don't think it matters, but I would use a local variable instead of a class level variable simply because it reduces coupling with other class methods.

遮了一弯 2024-10-18 12:56:48

当在方法内部使用“using”时,只有在 using 语句内初始化对象时,才会在 using 块关闭时释放该对象。
由于您的对象是在 using 块之外定义的,因此我不相信它会自动被处理,尽管它应该“关闭”,因为在程序的其余部分中仍然会引用它

When using "using" inside a method, only if the object is initialised inside the using statement will the object be disposed when the using block closes.
Since your object is defined outside of the using block, I don't believe it would automatically be disposed though it should be "closed" since there would still be a reference to it throughout the rest of the program

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