首页 > 解决方案 > C#(或任何其他代码,因为唯一需要的是逻辑) - 永久禁用先前条件的条件

问题描述

我需要知道一种简化的方法来获得一个条件,即永久“禁用”已经满足的先前条件的事件。

也许我没有使用正确的术语,但我会用一个例子来解释我需要什么。

有条件:

if (a > 10)
{
   print ("Correct");
}

让我们假设满足条件并按Correct原样打印消息,稍后满足下一个新条件(重要的是,在满足第一个条件之后):

if (a <= 10)
{
   print ("Incorrect");
}

我需要的是,当满足第二个条件时Correct,即使再次出现,第一条消息也不再显示a <= 10,所以我需要Correct永久“跳过”,永久“禁用”或它调用的正确方式,现在代替的 Correct,那么新的和永久显示的消息就可以了Incorrect。如您所见,在我描述的情况下,比因为一旦要显示的永久消息是(“永远”)Incorrect重要。Correcta <= 10Incorrect

一段时间以来,我一直在使用if+ else,和if+ else if,和if+ 和额外分离的一些不同组合if,但现在没有积极的结果,因为是的,Incorrect一旦满足第二个条件,我就会显示消息,但奇怪的原因是什么代码所做的是,一旦满足第二个条件,它就会同时在屏幕上显示消息,Correct并且Incorrect我不明白为什么会发生这种情况,因为这两个条件是互斥的,所以理论上,当其中一个是遇到了我认为是其他的自动“禁用”。我不知道这两个条件都进入循环的事实是否会产生任何特殊情况,因为这种情况正在发生。

...
// Here is an example of what I'm using. I tried to put the next in 
// around 10 different ways,either in the same part of the code or in 
// different parts and always the same result, it displays as 
// should `Correct` but when the `a <= 10` is met it displays both messages
// `Correct` and `Incorrect`, 
// and what I need is when this happens, only be displayed `Incorrect` permantly.

if (a <= 10)
{
   print ("Incorrect");
}
else if (a > 10)
{
   print ("Correct");
}
...

注意:我认为不需要额外的代码或上下文,因为这里我们讨论的是一个非常简单的逻辑,一个简单的代码。顺便说一句,我使用的是 C#,但我将示例与通用代码放在一起,因为我需要的主要是逻辑。

标签: c#if-statement

解决方案


如果你想要永久(不管a)条件,我们必须提取它:

  // true : initially, we should check a > 10 condition
  bool isCorrect = true;

请注意,此声明不应是局部变量,而是方法外的 ( static?)字段

  static bool isCorrect = true;

那么你可以使用isCorrecta > 10条件的组合

  // &&= looks more natural, however only &= operator exists
  if (isCorrect &= a > 10)
      print("Correct");
  else
      print("Incorrect");

您甚至可以在 turnary 运算符的帮助下将代码压缩在一个行中:

 print((isCorrect &= a > 10) ? "Correct" : "Incorrect");

请注意,只要a > 10不见面,false就会被分配到isCorrect,从现在开始isCorrect将是false


推荐阅读