在 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/