简体   繁体   中英

Why would you use the using statement this way in ASP.NET?

Refactoring some code again. Seeing some of this in one of the ASP.NET pages:

using (TextBox txtBox = e.Row.Cells[1].FindControl("txtBox") as TextBox)
{
}

There is no need to dispose txtBox, because it's just a reference to an existing control. And you don't want the control disposed at all. I'm not even sure this isn't harmful - like it would appear to ask for the underlying control to be disposed inappropriately (although I have not yet seen any ill effects from it being used this way).

TextBox inherits its implementation of IDisposable 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.

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.

The TextBox instance could potentially be null if not found, so Dispose() is called a NullReferenceException 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.

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语句括号内的上下文,这可能是使用它的主要原因。

From MSDN :

Within the using block, the object is read-only and cannot be modified or reassigned.

So I guess you can only read the textbox properties, but not change them, inside the using block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM