本文介绍了C#8使用声明范围混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的C#8使用声明语法,第二个连续using语句的范围是什么?

With the new C# 8 Using Declaration Syntax, what is containing scope of a second consecutive using statement?

TL; DR

C#8之前的版本,具有连续的using语句,例如:

Previous to C# 8, having a consecutive using statement like:

using(var disposable = new MemoryStream())
{
    using(var secondDisposable = new StreamWriter(disposable))
    {}
}

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

would expand to something like the following (My Source):

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();
}

我知道还有其他两种可能的扩展,但它们都大致是这样的

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

After upgrading to C# 8, Visual studio offered a Code Cleanup suggestion that I'm not certain I believe is an equivalent suggestion.

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

It converted the above consecutive using statement to:

using var disposable = new MemoryStream();
using var secondDisposable = new StreamWriter(disposable);

对我来说,这将第二个的范围更改为与第一个相同的范围.在这种情况下,它可能会以正确的顺序巧合地处理流,但是我不确定我是否希望依靠这种快乐的巧合.

To me this changes the second's scope to the same scope as the first. In this case, It would probably coincidentally dispose of the streams in the correct order, but I'm not certain I like to rely on that happy coincidence.

要明确VS要求我做什么:我首先转换了内部(这很有意义,因为内部仍然包含在外部的范围内).然后,我转换了外部函数(这在本地很有意义,因为它仍然包含在方法的作用域中).我很好奇这两个清理工作的结合.

我也认识到,我对此的想法可能会略有偏离(甚至显着),但是据我今天的理解,这似乎并不正确.我的评估中缺少什么?我在基地外吗?

I also recognize that my thinking on this could be slightly (or even dramatically) off, but as I understand it today, this doesn't seem correct. What is missing in my assessment? Am I off base?

我唯一能想到的是,对于声明语句之后的所有内容,扩展中都会插入某种隐式范围.

The only thing I can think of is that there is some sort of an implicit scope inserted in the expansion for everything following a declaration statement.

推荐答案

规格建议:

所以,是的,他们已经考虑过了,并按照预期的顺序进行处理,就像使用语句之前将其链接在一起一样.

So, yes, they already thought about it and do the disposal in the expected order, just as chained using statements would before it.

这篇关于C#8使用声明范围混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:03