c# - AND/OR 的 If 语句说明

标签 c# if-statement

很抱歉问这么简单的问题。我只需要澄清一下,因为有时我会混淆不同之处。

有人可以帮我解释以下 if 语句之间的区别吗?

sending = true;
if (sending && e.AssetType == AssetType.Notecard) //#1

对比

if ((sending) && (e.AssetType == AssetType.Notecard)) //#2

对比

if (sending || e.AssetType == AssetType.Notecard) //#3

对比

if ((sending) || (e.AssetType == AssetType.Notecard)) //#4

在这种特定情况下,我需要它来评估类似以下内容: “如果(发送 == true AND e.AssetType == AssetType.Notecard)”

在另一种情况下,我需要 if 语句来检查一个字符串和列表的内容,例如: "If(string == "Name"OR List.Contains("string"))

最佳答案

第一个和第二个语句是相同的(在这种情况下括号不是必需的,因为 C# 评估优先级!)

if (sending && e.AssetType == AssetType.Notecard)
if ((sending) && (e.AssetType == AssetType.Notecard))

正如:

if ((sending == true) && e.AssetType == AssetType.Notecard))
if ((sending) && (e.AssetType == AssetType.Notecard))

3° 和 4° 语句也会给出相同的结果,原因与上述相同:http://msdn.microsoft.com/en-us/library/6a71f45d.aspx

我会使用这些语句:

if (sending && (e.AssetType == AssetType.Notecard))

和:

if ((string == "Name") || List.Contains("string"))

(但请注意字符串比较模式,例如大小写和文化:

String.Compare(string, "Name", StringComparison.CurrentCultureIgnoreCase) == 0

比较字符串而不考虑大小写和当前文化)

关于c# - AND/OR 的 If 语句说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040533/

相关文章:

c# - System.Exception : Incorrect syntax I can't find the problem

c# - 使用 LINQ,如何根据部分字符串属性过滤集合?

c - 如何在c编程中以优化的方式打印10X10行和列的V?

c# - 转换带有千位分隔符的格式化十进制字符串

c# - AutoDiscoverURL 有什么用?

.net - 如果、IIf() 和 If()

arrays - 如何检查 Fortran 数组是否包含值?

PHP:检查变量是否存在,但是否具有等于某物的值

javascript - 检查条件是否与 Javascript 中数组的任何值匹配

c# - IAsyncResult 未完成并锁定 UI