![](/img/trans.png)
[英]Why to use using statement on DbTransaction in ADO.NET / C#?
[英]why we use nested using statement in c#?
using (StreamReader outFile = new StreamReader(outputFile.OpenRead()))
{
StreamReader resFile = new StreamReader(resultFile.OpenRead())
{ //Some Codes }
}
为什么上面的resFile object没有自动关闭?
我也在 using 语句中写了 resFile object 。 请解释using
语句。
你没有使用嵌套使用。 只有一个 using 语句。
嵌套使用示例:
using (...)
{
using (...)
{
...
}
}
您可能想要使用嵌套使用的原因是您有多个声明需要处理。
在这里找到 using 语句的官方解释: https://learn.microsoft.com/en-us/do.net/csharp/language-reference/keywords/using-statement
在您的示例中,您没有嵌套的 using 语句,正如 Mark 在他的回答中正确所说的那样。 (尽管您应该第二次使用 resFile Streamreader。
如果您想在“// Some Codes”部分同时使用 stream 阅读器,它们必须嵌套,因为 outFile 和 resFile 的实例仅在大括号内可用。
从 C#8 开始,可以使用“避免”嵌套的新方法。 参见: https://learn.microsoft.com/de-de/do.net/csharp/language-reference/proposals/csharp-8.0/using
using
是语法糖,基本上可以编译成以下内容:
原始代码:
using (var a = b)
{
c();
d();
}
脱糖代码:
{
var a;
try {
a = b;
c();
d();
} finally {
if (a != null) {
((IDisposable)a).Dispose();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.