using 语句以正确的方式调用对象的 Dispose 方法,并且(当您像之前展示的那样使用它时)还会在 Dispose 被调用时导致对象本身超出范围。在 using 块内,对象是只读的,不能被修改或重新分配。
这来自 这里。
花括号外的所有内容都被处理掉了,因此如果您不再使用对象,将其处理掉是非常好的选择。这是因为如果您有一个SqlDataAdapter对象,并且在应用程序生命周期中仅使用一次,并且只填充一个数据集并且不再需要它,您可以使用以下代码:
using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
// do stuff
} // here adapter_object is disposed automatically
当您使用using时,它将在using的范围结束时调用对象的Dispose()方法。因此,您可以在Dispose()方法中编写大量的清理代码。
一个要点:
如果您实现了IDisposable,请确保在Dispose()实现中调用GC.SuppressFinalize(),否则自动垃圾回收将尝试在某个时刻对其进行Finalize,这至少会浪费资源,如果您已经Dispose()了它。
虽然并不是非常重要,但是使用也可以在运行时更改资源。
是的,像之前提到的那样,它是可丢弃的,但是也许你不想让这些资源与其他资源不匹配,干扰程序的其他执行。因此你需要销毁它们以避免影响其他地方。
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
Rhino Mocks Record-playback Syntax 使用 using
语法,非常有趣。
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}