在 C# 中是否有一种简洁的方法来循环 true/false?
我在单元测试中有大约 20 行代码,我宁愿不复制来切换一个 boolean 值 true/false。
我可以将它分解成一个函数并调用它两次,但是嗯。这段代码感觉更像是我在迭代可能的值,而不是使用不同的参数执行不同的操作。即使我有一个函数,我也更喜欢循环遍历可能值的语法,而不是只调用它两次。
我可以像这样写一个for
循环...
bool toggle;
for (int i = 0; i < 2; i++)
{
toggle = i == 1;
}
但这看起来不是很干净。
我喜欢this syntax :
for (bool b : { false, true }) { /* ... */ }
但它看起来不会在 C# 中编译。
编辑:
根据 Jeroen 关于本地函数的建议和 Dmitry 的回答,这是我走的路线:
[TestMethod]
public void GetAndSetValue()
{
foreach (bool toggle in new [] { false, true })
{
GetAndSetValue(toggle);
}
void GetAndSetValue(bool toggle)
{
// details not important
}
}
合理的编码人员可以争论循环是否比两个函数调用更容易读取:
GetAndSetValue(false);
GetAndSetValue(true);
我更喜欢这个循环,所以我会继续使用它直到有人提示为止。干杯!
最佳答案
正确的语法是foreach
,而不是for
:
foreach (bool b in new [] { false, true }) {
/* ... */
}
关于C# 遍历 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51175996/