相关疑难解决方法(0)

C# 8 使用声明范围混淆

使用新的 C# 8 Using Declaration Syntax,包含第二个连续 using 语句的范围是什么?

TL; 博士

在 C# 8 之前,有一个连续的 using 语句,如:

using(var disposable = new MemoryStream())
{
    using(var secondDisposable = new StreamWriter(disposable))
    {}
}
Run Code Online (Sandbox Code Playgroud)

将扩展为以下内容(我的来源):

MemoryStream disposable = new MemoryStream();
try {
    {
        StreamWriter secondDisposable = new StreamWriter(disposable);    
        try{
            {}
        }
        finally {
            if(secondDisposable != null) ((IDisposable)secondDisposable).Dispose();
        }
    }
}
finally {
    if(disposable != null) ((IDisposable)disposable).Dispose();
}
Run Code Online (Sandbox Code Playgroud)

我知道还有另外两个可能的扩展,但它们都大致是这样的

升级到 C# 8 后,Visual Studio 提供了一个代码清理建议,我不确定我认为这是一个等效的建议。

它将上面的连续 using 语句转换为:

using var disposable = new MemoryStream(); …
Run Code Online (Sandbox Code Playgroud)

c# visual-studio c#-8.0 visual-studio-2019

11
推荐指数
1
解决办法
1120
查看次数

标签 统计

c# ×1

c#-8.0 ×1

visual-studio ×1

visual-studio-2019 ×1