我不确定是否有办法做到这一点,但我认为这是最好的地方。
我希望在使用它之后立即更改布尔值(或之前,只需要语义更改),但是在同一行中。 预期效果与此代码相同:
bool flag, tempFlag; //whatever names ... tempFlag = flag; flag = !flag;但我想知道是否有一种速记方式,只需一行即可。 有点像tempFlag = flag!; :P
例如,您可以在单行中使用其值后立即更改int的值,如下所示:
int x = y++;是否有一种简短的方式来编写这样的动作?
我的具体问题是在C#,但我很好奇,如果任何其他流行的语言有这样的方式。
I'm not sure if there's even a way to do it, but I figure this is the best place to ask.
I want to change a boolean's value immediately after using it (or before, would only require a semantic change), but in the same line. The intended effect would be the same as this code:
bool flag, tempFlag; //whatever names ... tempFlag = flag; flag = !flag;But I was wondering if there's a shorthand way of doing that, in a single line. Something like tempFlag = flag!; :P
For example, you can change the value of an int immediately after using its value in a single line, as in:
int x = y++;Is there a short way of writing such an action?
My specific problem is in C#, but I am curious if any other popular language has such a way.
最满意答案
tempFlag = !(flag = !flag);应该使用所有提到的语言。 flag = !flag返回新值,然后再次反转并放入tempflag 。 但正如NathanOliver所说,我认为没有必要做这样的事情。 如果你想要它是线程安全的(这是我能想象的唯一这样的应用程序,我甚至不确定它是否可行)使用线程锁来实现它。
tempFlag = !(flag = !flag);should work in all mentioned languages. flag = !flag returns the new value, which is then inverted again and put into tempflag. But as NathanOliver mentioned, I see no need to do something like this. If you want it to be threadsafe (which is the only application I can imagine for something like this, and I'm not even sure if it would work) use a thread lock to make it so.
更多推荐
发布评论