我经常看到并且在C ++中经常使用的一种常见模式是将变量暂时设置为新值,然后在退出该作用域时重置它。 在C ++中,可以使用引用和模板化的作用域类轻松实现这一点,并允许增加安全性以及防止变量被设置为新值,然后重置为错误的假定初始值。
以下是一个简化的示例(使用C ++):
void DoSomething()
{
// The following line captures GBL.counter by reference, stores its current
// value, and sets it to 1
ScopedReset<int> resetter(GBL.counter, 1);
// In this function and all below, GBL.counter will be 1
CallSomethingThatNeedsCounterOf1();
// When I hit the close brace, ~ScopedReset will be called, and it will
// reset GBL.counter to it's previous value
}
有没有办法在C#中实现这个功能?我已经发现,在IEnumerator或lambda中,我不能捕获ref参数,这是我的前两个想法。如果可能的话,我不想使用unsafe关键字。
IDisposable
和using
。 - Stephen Cleary