[C#] using语句,在哪里以及如何使用它 [英] [C#] using statement, where and how to use it

查看:218
本文介绍了[C#] using语句,在哪里以及如何使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我正在使用streamreader,streamwriter等。我想使用using语句,因为不需要.Close(),. Dispose(),...是吗?使用是否适合你?那会释放内存吗?

规则在哪里以及如何使用?



还有一件事:让我说我有一个streamreader的代码,我忘了使用.Close(),我在Visual Studio中可以看到(在调试时)我忘了它并且它使用了内存,...

In my app i am using streamreader, streamwriter, and so on. I would like to use using statement, because there is no need for .Close(), .Dispose(),... is that right? Using makes it for you? And that releases the memory?
What is the rule where and how to use using?

And one more thing: Let say that i have a code for streamreader and i forgot to use .Close(), where in Visual Studio can i see (while debuging) that i forgot it and that it uses memory,...

推荐答案





查看这些关于使用声明的文章:

理解C#中的''using''语句 [ ^ ]

C#中的使用关键字 [ ^ ]

http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx [ ^ ]
Hi,

Have a look at these articles about the ''using'' statement:
Understanding the ''using'' statement in C#[^]
The "using" Keyword in C#[^]
http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx[^]


不需要.Close(),



using语句将调用Dispose,Dispose将调用Close(在大多数具有Close的类中),但我仍然会将Close称为Close;没有理由不这样做。
"there is no need for .Close(),"

The using statement will call Dispose, and Dispose will call Close (in most classes that have a Close), but I still call Close as a matter of discipline; there''s no reason not to.


要添加PIEBALDconsult所说的,使用使用的另一个好处是不像Close或者Dispose,它还将变量的范围限制在它有效的代码段。

一旦你使用
块离开,变量超出范围,这意味着如果您尝试使用已经处理的变量,编译器会抱怨。



错字:小时 forgoes(平板电脑打字) - OriginalGriff [/ edit]
To add to what PIEBALDconsult says, the other advantage of using using is that unlike Close or Dispose, it also limits the scope of the variable to the section of code in which it is valid.
Once you leave the using block, the variable goes out of scope, which means that the compiler will complain if you try to use a variable which has been disposed.

[edit]Typo: "hours" for "goes" (tablet typing) - OriginalGriff[/edit]


这篇关于[C#] using语句,在哪里以及如何使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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