首页 > 解决方案 > C#模式块将变量设置为开始值,做一些工作并用结束值重置变量

问题描述

我正在尝试优化以下工作流程:

myObj.SupressEvents = true;
DoSomeWork();
DoSomeMoreWork();
...
myObj.SupressEvents = false;

这样做的问题很明显,要么myObj.SupressEvents = true/false;可能会在两者之间遗漏并导致不必要的错误,要么只是通过使用 return 可以使重置为 false 永远无法达到,我正在寻找一种避免忘记它的模式,例如:

// This is a keyword example, not a function call nor definition
SetAndReset(myObj.SupressEvents, true, false)
{
   DoSomeWork();
   DoSomeMoreWork();
   ...
}

我想这可以通过委托或具有 Func 的函数来完成,但是即使我在两者之间进行返回,它也可以工作,它会将变量重置为 false 吗?原生 C# 关键字中有类似的东西吗?

标签: c#delegates

解决方案


You can declare a method that takes an Action (the work you want to do) and wrap the calls inside that method:

void Wrap(Action action, object myObj /* Replace with actual type, or remove parameter if field in class */)
{
    myObj.SupressEvents = true;
    action.Invoke();
    myObj.SupressEvents = false;
}

You can call the method like so:

Wrap(() => 
{
    DoSomeWork();
    DoSomeMoreWork();
});

推荐阅读