开发者

C# - Check a bool for a value and then flip it

开发者 https://www.devze.com 2022-12-28 15:07 出处:网络
for (i开发者_如何学JAVAnt i = 0; i < X; i++) myitem = (checkedDB) ? dirtyItem : cleanItem; I wanted to know if there\'s a way of flipping checkedDB in the same statement, i.e. the next iteration
for (i开发者_如何学JAVAnt i = 0; i < X; i++)
   myitem = (checkedDB) ? dirtyItem : cleanItem;

I wanted to know if there's a way of flipping checkedDB in the same statement, i.e. the next iteration checkedDB is the opposite of it's value, so like XORing.


What about:

for (int i = 0; i < X; i++)
    myitem = !(checkedDB = !checkedDB) ? dirtyItem : cleanItem;

That may be not really readable/understandable at first sight, but it does what you want in one statement.


The best answer, IMO, is: not if you have any self-respect. The result will be ugly and confusing, and for no real gain. Here are two distinct solutions that are cleaner and thus easier to understand.

for (int i = 0; i < X; i++)
{
    myitem = checkedDB ? dirtyItem : cleanItem;
    checkedDB = !checkedDB;
}

The following version doesn't even require the extra variable and achieves your one-line goal:

for (int i = 0; i < X; i++)
{
    myitem = i%2 == 0 ? dirtyItem : cleanItem;
}


One way to toggle a boolean value is bool ^= true:

for (int i = 0; i < X; i++)
{
   myitem = (checkedDB ^= true) ? cleanItem : dirtyItem;
}

I swapped cleanItem and dirtyItem since you toggle checkedDB before one of them is chosen.

The benefit of using checkedDb ^= true over checkedDB = !checkedDB is that it is clear that you meant to modify checkedDB and didn't accidentally mistype a == comparison.

Since you haven't specified the language, I can't say for certain if your language will allow an assignment in the conditional part of the ternary operator.


The following should work, but may not be easily understandable:

for (int i = 0; i < X; i++)
    myitem = (checkedDB = !checkedDB ) ? cleanItem : dirtyItem ;

I agree that there should be some better and cleaner solution in the future and I'd recommend something like this:

for (int i = 0; i < X; i++)
{
    myitem = (checkedDB^^) ? dirtyItem : cleanItem;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消