c# - 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# 关键字中有类似的东西吗?
解决方案
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();
});
推荐阅读
- unity3d - 在 Unity 中,我可以在运行时修改使用地形编辑工具创建的地形网格,以便“挖”一个洞吗?
- python - 在Win10上运行Pip Install beautifulsoup4时出现EnvironmentError
- python - 无法从 Google Drive API 检索 thumbnailLink
- python - 为什么我不能使用 Screenmanager 和 ObjectProperty 访问我的图像源?
- javascript - 尝试替换对象属性值中的所有字符实例
- python - 当我写这会从 svg 文件中删除所有数据
- socket.io - 无法连接到套接字服务器
- android - viewpager2 的 TabLayoutMediator 在新的 android studio version4.0.0 上不可用
- c++ - 我的项目应该从哪里包含 new.h?(Visual Studio 和/或 SDK 损坏或版本不兼容?)
- c# - 通过算法从用户 ID 生成唯一的随机好友代码