Why are there no ||= or &&= operators in C#?

心不动则不痛 提交于 2019-12-17 16:34:04

问题


We have equivalent assignment operators for all Logical operators, Shift operators, Additive operators and all Multiplicative operators.

Why did the logical operators get left out? Is there a good technical reason why it is hard?


回答1:


Why did the logical operators get left out? Is there a good technical reason why it is hard?

They didn't. You can do &= or |= or ^= if you want.

bool b1 = false;
bool b2 = true;
b1 |= b2; // means b1 = b1 | b2

The || and && operators do not have a compound form because frankly, they're a bit silly. Under what circumstances would you want to say

b1 ||= b2;
b1 &&= b2;

such that the right hand side is not evaluated if the left hand side does not change? It seems like only a few people would actually use this feature, so why put it in?

For more information about the compound operators see my serious article here:

http://blogs.msdn.com/b/ericlippert/archive/2011/03/29/compound-assignment-part-one.aspx

and the follow-up April-Fools article here:

http://blogs.msdn.com/b/ericlippert/archive/2011/04/01/compound-assignment-part-two.aspx




回答2:


maybe just use

isAdmin = isAdmin || IsGroupAdmin()

I guess it is partially because a ||= b is kind of confusing because there might be two versions of the implementation: a = a || b, or a = b || a. And they act differently because the right-hand side of the expression is sometimes not evaluated.



来源:https://stackoverflow.com/questions/6346001/why-are-there-no-or-operators-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!