For example:
using (disposable object here)
{
}
What determines if 开发者_运维知识库I can use an object in this way?
Would this work correctly?
using (WebClient webClient = new WebClient())
{
}
In order to be used in a using statement, a class needs to implement the IDisposable interface.
In your example, WebClient derives from Component, which implements IDisposable
, so it would indeed work.
You can use it if the class implements the IDisposable
interface. This keyword is basically just syntactic sugar for calling the object's IDisposable.Dispose()
method automatically after the using
block.
The Dispose()
method:
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
The object provided in the using statement must implement the IDisposable interface.
This interface provides the Dispose method, which should release the object's resources.
Reference: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx
It works if the object implements IDisposable
.
WebClient
inherits from Component
which does implement IDisposable
so your code should work.
If it didn't work you should get a compile time error.
精彩评论