用户科科斯通过提到using
关键字回答了精彩的https://stackoverflow.com/questions/9033/hidden-features-of-c问题。你能详细说明一下吗?using
的用途是什么?
发布于 2008-09-16 18:30:43
using
语句的原因是确保对象一旦超出作用域就被释放,并且它不需要显式代码来确保这种情况的发生。
与https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C和https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects一样,C#编译器会转换
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
至
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8引入了一个名为“使用声明”的新语法:
using声明是一个变量声明,前面有using关键字。它告诉编译器,被声明的变量应该在封闭作用域的末尾释放。
因此,上面的等效代码是:
using var myRes = new MyResource();
myRes.DoSomething();
当控件离开包含的作用域(通常是方法,但也可以是代码块)时,myRes
将被释放。
发布于 2008-09-16 19:11:57
因为很多人仍然这样做:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
我想很多人还是不知道你能做什么:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
发布于 2008-09-16 18:26:00
就像这样:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
这个try
/catch
/finally
.将被关闭,而不需要显式调用.Close()
函数,即使抛出异常也会发生这种情况,而不需要一个.Close()
。
https://stackoverflow.com/questions/75401
复制相似问题