所以当 using block 退出时,using 语句会自动调用正在“使用”的对象上的 dispose 方法,对吗?
但什么时候这是必要的/有益的?
例如,假设您有这个方法:
public void DoSomething()
{
using (Font font1 = new Font("Arial", 10.0f))
{
// Draw some text here
}
}
既然对象是在方法中创建的,这里有必要用using语句吗?当方法退出时,字体对象是否会被丢弃?
或者 Dispose 方法是否在方法退出后的另一个时间运行?
例如,如果方法是这样的:
public void DoSomething()
{
Font font1 = new Font("Arial", 10.0f);
// Draw some text here
}
// Is everything disposed or cleared after the method has finished running?
最佳答案
“using”语句在处理非托管对象(如数据库连接)时最有用。
这样,无论代码块中发生什么,连接都会被关闭和释放。
有关更多讨论,请参阅 CodeProject 上的这篇文章: http://www.codeproject.com/KB/cs/tinguusingstatement.aspx
关于c# - C# "using"语句什么时候最有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/752581/