IF AND OR C#的语法是什么

时间:2016-08-12 12:42:47

标签: c# if-statement

我正在尝试做IF(SOMETHING&& NOT)或(SOMETHING&& NOT)...但它不起作用,你能看出我做错了吗?

if (MyBeam.Position.Rotation == Position.RotationEnum.FRONT &&
!(MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS")

||

(MyBeam.Position.Rotation == Position.RotationEnum.BACK &&
!(MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS")))))

忽略对API的引用,但我相信它仍然有意义。

3 个答案:

答案 0 :(得分:2)

你的括号错了。这应该工作:

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT &&
     !(MyBeam.Profile.ProfileString.Contains("RHS") || 
       MyBeam.Profile.ProfileString.Contains("CHS") || 
       MyBeam.Profile.ProfileString.Contains("MET") || 
       MyBeam.Profile.ProfileString.Contains("SHS"))) ||
    (MyBeam.Position.Rotation == Position.RotationEnum.BACK &&
     !(MyBeam.Profile.ProfileString.Contains("RHS") || 
       MyBeam.Profile.ProfileString.Contains("CHS") || 
       MyBeam.Profile.ProfileString.Contains("MET") || 
       MyBeam.Profile.ProfileString.Contains("SHS"))))

那就是说,这是非常难以理解的。尝试将其中一些组合成变量,例如:

bool profileCheck = MyBeam.Profile.ProfileString.Contains("RHS") || MyBeam.Profile.ProfileString.Contains("CHS") || 
                    MyBeam.Profile.ProfileString.Contains("MET") || MyBeam.Profile.ProfileString.Contains("SHS");

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT && !profileCheck) ||
    (MyBeam.Position.Rotation == Position.RotationEnum.BACK && !profileCheck))

在这种形式中,我可以看到它可以简化:

if (!profileCheck && (MyBeam.Position.Rotation == Position.RotationEnum.FRONT || MyBeam.Position.Rotation == Position.RotationEnum.BACK))

答案 1 :(得分:0)

你是说你希望轮换是前面还是前面而你不想要RHS但是接受CHS,MET,SHS?

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT || MyBeam.Position.Rotation == Position.RotationEnum.BACK) &&
(
!MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS")
)
)

或者如果它是你说你想要旋转是前面还是后面而你不想要任何RHS,CHS,MET,SHS?

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT || MyBeam.Position.Rotation == Position.RotationEnum.BACK) &&
 !(
MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS")
)
)

答案 2 :(得分:0)

你的不是部分似乎不正确。您需要NOT所有OR条件

if ((MyBeam.Position.Rotation == Position.RotationEnum.FRONT || MyBeam.Position.Rotation == Position.RotationEnum.BACK) &&
!((MyBeam.Profile.ProfileString.Contains("RHS")
|| MyBeam.Profile.ProfileString.Contains("CHS")
|| MyBeam.Profile.ProfileString.Contains("MET")
|| MyBeam.Profile.ProfileString.Contains("SHS"))