为什么要在 ASP.NET 中以这种方式使用 using 语句?
再次重构一些代码。在 ASP.NET 页面之一中看到其中的一些内容:
using (TextBox txtBox = e.Row.Cells[1].FindControl("txtBox") as TextBox)
{
}
无需处置 txtBox,因为它只是对现有控件的引用。而且您根本不希望释放该控件。我什至不确定这是否有害 - 就像它似乎要求不恰当地处理底层控件一样(尽管我还没有看到这种方式使用它带来的任何不良影响)。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
TextBox
从其 组件超类。如果该实现会从其站点容器中删除该组件,则有一个。因此,如果文本框实际上驻留在站点容器中,那么这样做可能会产生不良影响。另外,在对对象调用
Dispose()
后,无论如何都不应该再次使用它(它不再处于可用状态)。我建议您使用 ASP.NET Web 控件避免这种模式。
TextBox
inherits its implementation ofIDisposable
from its Component superclass. That implementation removes the component from its site container if it has one.So, doing that might have nefarious effects if the text box actually resides in a site container. Also, after calling
Dispose()
on an object, you should not use it again, no matter what (it's not in a usable state anymore).I'd suggest you avoid that pattern with ASP.NET web controls.
这是错误的,不应该这样使用。我想使用这个可能会出现一些不会立即出现的潜在问题。文本框 dispose 在离开 using 语句时被调用,但不会立即被垃圾收集。如果它被收集,那么稍后当您尝试访问该控件时将会遇到问题。
This is wrong, it shouldnt be used like this. I would imagine there are potential problems using this that wont show up immediately. The textboxes dispose is called upon leaving the using statement but it wont be garbage collected immediately. If it is collected then you will have problems later when you try to access that control.
如果未找到,
TextBox
实例可能为 null,因此调用 Dispose() 并会抛出NullReferenceException
。我在实践中从未见过这种模式,但如果您需要使用它,那么处理任何潜在的错误都是值得的。
The
TextBox
instance could potentially be null if not found, so Dispose() is called aNullReferenceException
would be thrown.I've never seen that pattern in practice, but if you need to use it, it'd be worth handling any potential errors.
不应该有负面的副作用,但也没有必要。如果我们对 CLR 中实现 IDisposable 的所有内容都使用 (x) { ... },则大多数 C# 代码将不可读。
There should be no negative secondary effects, but it's not necessary either. If we did
using (x) { ... }
on everything that implements IDisposable in the CLR most C# code would be unreadable.实际上,这里的 TextBox 实例只能被 using 语句括号内的上下文访问,也许这就是使用它的主要原因。
Actually, here the TextBox instance is accessible only to the context inside the brackets of using statement, maybe that was the main reason of using it.
来自 MSDN:
所以我猜你只能在 using 块内读取文本框属性,但不能更改它们。
From MSDN:
So I guess you can only read the textbox properties, but not change them, inside the using block.