如果是C#"采用"声明最有用? [英] When are C# "using" statements most useful?

查看:147
本文介绍了如果是C#"采用"声明最有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以using语句自动调用正被拿来主义,当使用退出块吧?



在对象上的Dispose方法但当这?需要/有益



例如假设你有这样的方法:

 公共无效DoSomething的()
{
使用(字体font1 =新的字体(宋体,10.0f))
{
//绘制一些文字在这里
}
}

是否有必要在这里有using语句,因为对象是在方法创建?当方法退出,惯于Font对象进行处理呢?



抑或是Dispose方法获取方法退出后,在其他时间运行?



例如,如果该方法是这样的:

 公共无效DoSomething的()
{
字体font1 =新的字体(宋体,10.0f);

//绘制一些文字在这里
}

//被处置,或者该方法已完成运行后,清除一切吗?


解决方案

在'使用'一起工作时,语句是最有用的非托管对象,例如数据库连接。



在这种方式中,连接被关闭,设置不管在代码块发生



有关的更多讨论,请参见本文在CodeProject:
HTTP:// WWW。 codeproject.com/KB/cs/tinguusingstatement.aspx


So a using statement automatically calls the dispose method on the object that is being "used", when the using block is exited, right?

But when is this necessary/beneficial?

For example let's say you have this method:

public void DoSomething()
{
    using (Font font1 = new Font("Arial", 10.0f))
    {
        // Draw some text here
    }
}

Is it necessary to have the using statement here, since the object is created in the method? When the method exits, wont the Font object be disposed of anyway?

Or does the Dispose method get run at another time after the method exits?

For example if the method was like this:

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?

解决方案

The 'using' statement is most useful when working with unmanaged objects, like database connections.

In this way, the connection is closed and disposed no matter what happens in the code block.

For more discussion, see this article on CodeProject: http://www.codeproject.com/KB/cs/tinguusingstatement.aspx

这篇关于如果是C#"采用"声明最有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆