c# - 什么是 IF 语句中的 OR 运算符

标签 c# conditional-operator

在 C# 中,如何指定 OR:

if(this OR that) {do the other thing}

我在帮助里找不到。

更新:

我的代码是:

if (title == "User greeting" || "User name") {do stuff}

我的错误是:

Error 1 Operator '||' cannot be applied to operands of type 'bool' and 'string' C:\Documents and Settings\Sky View Barns\My Documents\Visual Studio 2005\Projects\FOL Ministry\FOL Ministry\Downloader.cs 63 21 FOL Ministry

最佳答案

|| 是 C# 中的条件或运算符

您可能很难找到它,因为很难搜索您不知道其名称的内容。下次尝试在 Google 上搜索“C# Operators”并查看逻辑运算符。

Here is a list C# 运算符。

My code is:

if (title == "User greeting" || "User name") {do stuff};

and my error is:

Error 1 Operator '||' cannot be applied to operands of type 'bool' and 'string' C:\Documents and Settings\Sky View Barns\My Documents\Visual Studio 2005\Projects\FOL Ministry\FOL Ministry\Downloader.cs 63 21 FOL Ministry

您需要这样做:

if (title == "User greeting" || title == "User name") {do stuff};

OR 运算符以相同的方式计算两边的表达式。在您的示例中,您正在对表达式 title == "User greeting" ( bool 值)和表达式 "User name" (字符串)进行操作。如果不进行转换或转换,就不能直接组合这些,这就是您收到错误的原因。

此外,值得注意的是,|| 运算符使用了“短路求值”。这意味着如果第一个表达式的计算结果为 true,则不会计算第二个表达式,因为它不一定是 - 最终结果将始终为 true。有时您可以在优化过程中利用这一点。

最后一个简短的说明 - 我经常用这样的嵌套括号编写我的条件:

if ((title == "User greeting") || (title == "User name")) {do stuff};

这样我就可以控制优先级,而不必担心操作顺序。它在这里可能有点矫枉过正,但当逻辑变得复杂时它特别有用。

关于c# - 什么是 IF 语句中的 OR 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158580/

相关文章:

c# - 在当前打开的应用程序顶部显示隐藏的窗口窗体

python - python中三元运算符的缩写

c - 三元(条件)表达式的类型错误

ruby - 如何使用条件运算符 (?:) in Ruby?

c# - 低级鼠标 Hook 不会在管理进程上触发 mousedown/mouseup 事件

c# - 精确文本匹配的 NEST 查询

c# - 将子线程与主线程同步 - 不是那么明显的问题

c# - 为什么在更改 ItemsSource 时 DataGrid 不更新?

c++ - 看不懂逗号表达

java - 为什么 System.out.print(三元运算符) 在输出中打印 float ?