What are the uses of “using” in C#

2018-12-31 02:42发布

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?

29条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 03:12

The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.

using (Font font2 = new Font("Arial", 10.0f))
{
    // use font2
}

See here for the MSDN article on the C# using keyword.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 03:12

For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.

A different name for error handling would've been nice, and maybe a somehow more obvious one.

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 03:13

In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.

If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.

Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.


1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.

查看更多
余欢
5楼-- · 2018-12-31 03:15

using as a statement automatically calls the dispose on the specified object. The object must implement the IDisposable interface. It is possible to use several objects in one statement as long as they are of the same type.

The CLR converts your code into MSIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in IL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.

查看更多
笑指拈花
6楼-- · 2018-12-31 03:16

using is used when you have a resource that you want disposed after it's been used.

For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.

The resource being used needs to implement IDisposable to work properly.

Example:

using (File file = new File (parameters))
{
    *code to do stuff with the file*
}
查看更多
登录 后发表回答