在 C# 中是否有一种简洁的方法来循环 true/false?
我在单元测试中有大约 20 行代码,我不想重复来切换一个布尔值真/假。
我可以将它分解成一个函数并调用它两次,但是呃。这段代码感觉更像是我在迭代可能的值,而不是使用不同的参数执行不同的操作。即使我有一个函数,我也更喜欢循环可能的值的语法,而不是仅仅调用它两次。
我可以像这样写一个
for
循环...
bool toggle;
for (int i = 0; i < 2; i++)
{
toggle = i == 1;
}
但是看起来不太干净。
我喜欢这个语法:
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# 中可以获得的最接近 C++11 语法的是:
foreach (bool value in new [] { false, true })
{
// ...
}
我可能会这样做,或者使用本地函数:
[TestMethod]
public void GetAndSetValue()
{
GetAndSetValue(false);
void GetAndSetValue(bool toggle)
{
// details not important
if (!toggle)
GetAndSetValue(true);
}
}
或者采用私人方法的“老”学校。
[TestMethod]
public void GetAndSetValue()
{
GetAndSetValue(false);
}
private void GetAndSetValue(bool toggle)
{
// details not important
if (!toggle)
GetAndSetValue(true);
}
聚会有点晚了 - 但这是我想出的一个不同的解决方案:
for ((bool b, int n) = (false, 0); n < 2; b = true, n++) {
/* ... */
}
它适用于 C# 7.3,因此与 .NET Framework 兼容。
很晚了,但我是这样做的:
bool High = false;
for (int i = 0; i < 2; i++)
{
//Other code
queues[7].Enqueue(new Values {//....
High = !High; // Toggle the value of High
}