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 (Text开发者_JS百科Box 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.
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.
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.
精彩评论