简体   繁体   English

如何使用C#使用多个条件运算符

[英]How to use multiple conditional operators using C#

I want to use combination of the 2 operators: the && and the || 我想使用两个运算符的组合:&&和|| operator using C#. 使用C#的运算符。 I have 5 variables that I would like to make sure if these conditions are met. 我有5个变量,我想确定是否满足这些条件。 varRequestedDate varTotdayDate varExpectedDate Approval1 Approval2 Here is what I have for my current condition but would like to add other variables adding the OR operator: varRequestedDate varTotdayDate varExpectedDate Approval1 Approval2这是我目前的状况,但想添加其他变量来添加OR运算符:

if (varRequestedDate != ("&nbsp;") && varExpectedDate < varTotdayDate)

here is the pseudocode for what I would like to see after the updated version: 这是我希望在更新版本后看到的伪代码:

(if varRequestedDate is not blank 
and varExpectedDate is less than varTotdayDate
and either Approved1 OR Approved2 = Yes)
send email()

i cannot figure out how to do this. 我不知道该怎么做。 thanks 谢谢

You just have to add nested parentheses: 您只需要添加嵌套括号即可:

if (varRequestedDate != "&nbsp;" 
    && varExpectedDate < varTotdayDate
    && (Approved1 == "Yes" || Approved2 == "Yes")
)
    sendEmail();

For the sake of readability and expressiveness I would extract the boolean values into meaningfully named variables: 为了便于阅读和表达,我将布尔值提取到有意义的命名变量中:

var isDateRequested = varRequestedDate != ("&nbsp;");
var isDateWithinRange = varExpectedDate < varTotdayDate;
var isApproved = Approved1 == "Yes" || Approved2 == "Yes";

if (isDateRequested && isDateWithinRange && isApproved)
{...}

You can nest logical operators using parentheses (just like arithmetic operators). 您可以使用括号嵌套逻辑运算符(就像算术运算符一样)。 Otherwise they follow a defined precedence going left to right. 否则,它们遵循从左到右的定义优先级。

if (
    varRequestedDate !=("&nbsp;") && 
    varExpectedDate < varTodayDate && 
    (Approved1==Yes||Approved2==yes))

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

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