c#中Using块的目的是什么?它和局部变量有什么不同?
当前回答
从MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible. The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
换句话说,using语句告诉. net一旦不再需要using块中指定的对象,就释放它。
其他回答
using (B a = new B())
{
DoSomethingWith(a);
}
等于
B a = new B();
try
{
DoSomethingWith(a);
}
finally
{
((IDisposable)a).Dispose();
}
using语句用于处理c#中实现IDisposable接口的对象。
IDisposable接口有一个名为Dispose的公共方法,用于释放对象。当我们使用using语句时,我们不需要在代码中显式地处理对象,using语句会处理它。
using (SqlConnection conn = new SqlConnection())
{
}
当我们使用上面的代码块时,内部生成的代码是这样的:
SqlConnection conn = new SqlConnection()
try
{
}
finally
{
// calls the dispose method of the conn object
}
更多细节请阅读:理解c#中的“using”语句。
using语句获取一个或多个资源,执行一条语句,然后处置资源。
从MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible. The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
换句话说,using语句告诉. net一旦不再需要using块中指定的对象,就释放它。
还要注意,通过using实例化的对象在using块中是只读的。请参考这里的官方c#参考。
推荐文章
- Selenium c# WebDriver:等待元素出现
- 我如何添加双引号的字符串,是在一个变量?
- 如何创建数组。包含不区分大小写的字符串数组?
- 检查字符串是否包含字符串列表中的元素
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"