简体   繁体   中英

C# Logical Operator

Iam Working on an application where I need to get a boolean flag value, f , based on the values in two other boolean variables a and b . The following are the conditions:

  1. If both a and b are true f is true .
  2. If both a and b are false f is true .
  3. If a is true and b is false f is true .
  4. If a is false and b is true f is false

I'd like to know if there is a simpler way (like a single operator) to obtain the value of f other than what I have:

a?true:(b?false:true)

a ? true : cond a ? true : cond is equivalent to a || cond a || cond and b ? false : true b ? false : true is the same as !b so you can use:

bool result = a || !b;

What are you looking for is Logical Implication in inverse Direction:

a<=b

a    1 1 0 0 
b    1 0 1 0
a<=b 1 1 0 1 

Edit:I didn't give good explanation on my answer, regarding C# explanation and what actually Logical Implication is:

First, the => is the formal symbol for if...then .

P => Q means If P then Q.

Logical implication is rather intuitive, because we can transfer it most cases to natural language. Example:

If n>3, then n+1 >3

which is obviously true.

Bare something in mind - Citing Logical Reasoning: First Course :

In ordinary language, 'if...then' has a double meaning. Imagine that you say 'If it is raining, then I will not come'. Often this also means 'But if it is not raining, then I will come.It is true that you have not uttered this last sentence, however, a little common sense can lead to the conclusion of the last sentence.

There is a very good explanation on how to use Logical Implication In C# on this link : https://ericlippert.com/2015/11/05/logical-implication/

Furthermore, Lee's Answer is indeed correct. Logical implication in format

a=>b in C# is (!a || b)

Hence, answer to the question will be

a<=b in C# is (a||!b)

When I broke down your rules into simpler terms, I got:

  1. if a == b , f is true
  2. otherwise, f == a

So, one simple form of this expression would be:

f = (a == b) || a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM