变量具有空值但是仍然会调用语句

时间:2017-04-04 13:10:02

标签: c#

我有一个if语句

if (materialtype != "WINDOWVINYLREPL"
    || materialtype != "ROOFING"
    && materialtype != "null"
    && materialtype != null)
{                
    subtype = (from a in UEF.MaterialSubTypes 
               where a.MaterialSubType1.Equals(subtype) && a.Code.Contains(materialtype) 
               select a.Code).FirstOrDefault();
}

即使materialtype等于null,if语句仍然被调用,它不应该是

5 个答案:

答案 0 :(得分:9)

if (materialtype != "WINDOWVINYLREPL" || ...

变量为null所以当然它不等于“WINDOWVINYLREPL”,因此这个条件为真,它会进入。

答案 1 :(得分:0)

您有OR ||条件。应该是这样的:

if (materialtype != "WINDOWVINYLREPL" && materialtype != "ROOFING" && materialtype != "null" && materialtype != null)
    {                
        subtype = (from a in UEF.MaterialSubTypes where a.MaterialSubType1.Equals(subtype) && a.Code.Contains(materialtype) select a.Code).FirstOrDefault();
    }

答案 2 :(得分:0)

条件不是用适当的括号写的。 AND,或冲突

if ((materialtype != "WINDOWVINYLREPL") || (materialtype != "ROOFING" && materialtype != "null")) && materialtype != null)
    {                
        subtype = (from a in UEF.MaterialSubTypes where a.MaterialSubType1.Equals(subtype) && a.Code.Contains(materialtype) select a.Code).FirstOrDefault();
    }

答案 3 :(得分:0)

您的情况相当于:

if((materialtype != "WINDOWVINYLREPL") || (materialtype != "ROOFING" && materialtype != "null" && materialtype != null))

如果materialtype == null,则为真,因为(materialtype != "WINDOWVINYLREPL")为真。

&&运算符的优先级高于||

答案 4 :(得分:0)

尝试使用括号分隔逻辑“ OR ”和“” 因为如果值为null,则测试始终为真

if ((materialtype != "WINDOWVINYLREPL" || materialtype != "ROOFING")
        && materialtype != null)
    {   
      .....
    }