c# 中如果条件不相等

问题描述 投票:0回答:2

我有一个条件,该值不应为空,或者应该为

R
U

我已经尝试过以下方法,但仍然无法获得成功的结果。

if (Place == "" || Place != "R" || Place != "U")
{
    response.Status = "FAILURE";
    response.Message = "Place Criteria is required / Invalid (place should be either R(rural)/U(urban)";
}

即使我通过了

R
U
,它也会显示错误消息。

c# asp.net
2个回答
1
投票

我建议

else if
构建;这里我们有
2
有效 选项(农村和城市),所有其他选项都是不正确的:

 if (Place == "R")
   RuralRoutine(); //TODO: put the right code here
 else if (Place == "U")
   UrbanRoutine(); //TODO: put the right code here
 else { // All the other options are invalid
   response.Status = "FAILURE";
   response.Message = 
     "Place Criteria is required / Invalid (place should be either R(rural)/U(urban)";
 }

请注意,如果您想为“工业区”添加

"I"
,您只需再添加一个
else if
:

 ...
 else if (Place == "I")
   IndustrialAreaRoutine();
 else {  
   response.Status = "FAILURE";
   ...

0
投票
if(Place ==""||( Place!="R" && Place !="U"))
{

}

您希望 Place 不为 null 并且为“R”或“U”,因此您应该使用 && 来确保 3(null,"R","U") 不会同时发生。

© www.soinside.com 2019 - 2024. All rights reserved.