-1

我想知道如果我需要在它自己的 using() 标记中重新实例化一个变量,行为是什么(如果它已定义)?

我有一个实际的用例,使用 SharpDX 我有我想在渲染循环之外声明的变量(用于每个帧),我理想地包装为 thisusing(thevariable){MainLoop{}}; 但是如果发生某些事情(用户调整大小),该变量可能需要被处理和重新初始化。我在示例中看到它被初始化为null,然后在需要时在循环中重新初始化,重新处理,然后在循环之后再次处理,这看起来比使用好,使用语句要糟糕得多,所以我想知道会是什么代码的行为,例如:

void Main()
{
    using(var MyDisposable = new MyDisposable())
    {
        If(SomeCondition)
        {
             MyDisposable.Dispose() // Do i need to call this? Or is it auto called thanks to using when leaving the block? What will using call dispose on, the object that MyDisposable refers to, or the one it refered to back when i called the using statement?
             MyDisposable = new MyDisposable(); // Is this going to be managed by the using block? Is this even valid?
        }
    }
}

另外我不确定行为是否会随着时间而改变,我假设不会,但如果确实如此,我对 .net 4.5 答案感兴趣

4

1 回答 1

2

我想你会发现这会导致编译器错误..特别是:

无法分配给“MyDisposable”,因为它是“使用变量”

所以,你的问题的答案是:在这种情况下什么都没有发生。你的代码不会编译。

于 2013-10-15T04:28:08.860 回答