简体   繁体   English

C#逻辑运算符

[英]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 . Iam正在一个应用程序上,我需要基于其他两个布尔变量ab的值来获取布尔标志值f The following are the conditions: 以下是条件:

  1. If both a and b are true f is true . 如果ab都为真,则ftrue
  2. If both a and b are false f is true . 如果ab均为假,则ftrue
  3. If a is true and b is false f is true . 如果a为true且b为false,则ftrue
  4. If a is false and b is true f is false 如果a为假而b为真ffalse

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: 我想知道是否有一种简单的方法(如单个运算符)来获取f的值,而不是我拥有的值:

a?true:(b?false:true)

a ? true : cond a ? true : cond is equivalent to a || cond a ? true : cond等效于a || cond a || cond and b ? false : true a || condb ? false : true b ? false : true is the same as !b so you can use: b ? false : true!b相同,因此您可以使用:

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: 编辑:我没有对我的答案给出很好的解释,关于C#解释以及实际的逻辑含义是:

First, the => is the formal symbol for if...then . 首先,=>是if ... then的形式符号。

P => Q means If P then Q. P => Q表示如果P则Q。

Logical implication is rather intuitive, because we can transfer it most cases to natural language. 逻辑含义非常直观,因为我们可以将大多数情况转换为自然语言。 Example: 例:

If n>3, then n+1 >3 如果n> 3,则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/ 关于如何在此链接上使用C#中的逻辑含义的一个很好的解释: 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) C#中的a => b是(!a || b)

Hence, answer to the question will be 因此,问题的答案将是

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

When I broke down your rules into simpler terms, I got: 当我将您的规则分解成更简单的术语时,我得到了:

  1. if a == b , f is true 如果a == bftrue
  2. otherwise, f == a 否则, f == a

So, one simple form of this expression would be: 因此,此表达式的一种简单形式为:

f = (a == b) || a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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