变量作用域和“使用” .NET 中的语句
如果变量位于类级别(即 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 MSDN:
因此,从技术上讲,它会起作用,因为它将按照设计进行编译、运行和执行。但这可能不是一个好主意,并且不会产生非常直观的代码。
From MSDN:
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.
我认为这并不重要,但我会使用局部变量而不是类级别变量,因为它减少了与其他类方法的耦合。
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.
当在方法内部使用“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