用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?
当前回答
比如:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
这个SqlConnection将被关闭,而不需要显式地调用. close()函数,并且即使抛出异常也会发生,而不需要try/catch/finally。
其他回答
当您希望在使用某个资源后将其销毁时,将使用Using。
例如,如果您分配了一个File资源,并且只需要在一段代码中使用它进行少量的读写,使用有助于在完成后立即处理File资源。
所使用的资源需要实现IDisposable才能正常工作。
例子:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
当你使用using时,它将调用using作用域末端对象上的Dispose()方法。因此,在Dispose()方法中可以有相当多出色的清理代码。
要点:
如果您实现了IDisposable,请确保在Dispose()实现中调用GC.SuppressFinalize(),否则自动垃圾收集将尝试出现并在某个时刻Finalize它,如果您已经Dispose()d了它,这至少会浪费资源。
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
这允许您使用非常好的使用语法来指示所述操作的显式开始和结束。这也是系统如何。事务处理可以工作。
对我来说,“using”这个名字有点令人困惑,因为它可以是一个导入Namespace的指令,也可以是一个用于错误处理的语句(就像这里讨论的那样)。
为错误处理取一个不同的名字会很好,而且可能是一个更明显的名字。
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.
}
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间