具有2个操作的单行if语句的C#编译器错误

Era*_*cer 1 c# if-statement compiler-errors

很难找到解释这个问题的好标题.我将尝试详细解释这个问题.我尝试在另一个if语句中使用带有2个动作的单行if语句.但是,这种用法会失败父if语句的结果.

在深入研究之前,我必须强调下面的方法返回FALSE:

draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () 
Run Code Online (Sandbox Code Playgroud)

上面的方法包含在下面的两个if子句中.因此我希望结果立即为FALSE.唯一不变的部分是最后一个声明,重点放在那里.

没有括号的有问题的版本:

if (acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
        && draggedItem.GetComponent<PreparedItem> () != null 
        && draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
        && rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
        && draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
        && (true)? true : true) { // problem here 

        'if' is considered as TRUE and the inside is executed ...


}
Run Code Online (Sandbox Code Playgroud)

带括号的工作版本:

if (acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
        && draggedItem.GetComponent<PreparedItem> () != null 
        && draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
        && rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
        && draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
        && ((true)? true : true)) { // WORKS AS EXPECTED 

        'if' is considered as FALSE which is expected and the inside is NOT executed ...


}
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 6

考虑一下:

bool a = true;
bool b = false;

Console.WriteLine(a && b && (true) ? true : true);   // Prints true
Console.WriteLine(a && b && ((true) ? true : true)); // Prints false
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为运算符的优先级?:使得在上面的第一个WriteLine中,就好像你写了这样:

(a && b && (true)) ? true : true
Run Code Online (Sandbox Code Playgroud)

这总是会导致true.

当然,第二个是括号,以便它按预期工作.