c# - C#(或任何其他代码,因为唯一需要的是逻辑) - 永久禁用先前条件的条件
问题描述
我需要知道一种简化的方法来获得一个条件,即永久“禁用”已经满足的先前条件的事件。
也许我没有使用正确的术语,但我会用一个例子来解释我需要什么。
有条件:
if (a > 10)
{
print ("Correct");
}
让我们假设满足条件并按Correct
原样打印消息,但稍后满足下一个新条件(重要的是,在满足第一个条件之后):
if (a <= 10)
{
print ("Incorrect");
}
我需要的是,当满足第二个条件时Correct
,即使再次出现,第一条消息也不再显示a <= 10
,所以我需要Correct
永久“跳过”,永久“禁用”或它调用的正确方式,现在代替的 Correct
,那么新的和永久显示的消息就可以了Incorrect
。如您所见,在我描述的情况下,比因为一旦要显示的永久消息是(“永远”)Incorrect
更重要。Correct
a <= 10
Incorrect
一段时间以来,我一直在使用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#,但我将示例与通用代码放在一起,因为我需要的主要是逻辑。
解决方案
如果你想要永久(不管a
)条件,我们必须提取它:
// true : initially, we should check a > 10 condition
bool isCorrect = true;
请注意,此声明不应是局部变量,而是方法外的 ( static
?)字段:
static bool isCorrect = true;
那么你可以使用isCorrect
和a > 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
。
推荐阅读
- java - 如何自动(在键入时)扩展和缩小 EditTexts 的列以显示所有符号?
- python - 网球路线的 3D 模拟
- mysql - 如何从 MySQL DB 中的对象数组中获取和显示特定值?
- java - java中的dhtmlx grid.render_table不起作用
- d3.js - 创建美国东南部的 TopoJson/GeoJson 地图
- node.js - getSignedUrl 中的 URL 将在几周后过期
- ios - 可以在其中初始化约束的推荐 UIViewController 覆盖方法是什么?
- apache - 在 Win 10 上使用 Dev Desktop 等待响应 5 分钟后出现 Apache 内部服务器错误
- docker - 我可以将 Docker 运行参数传递给可选的 Golang 标志吗?
- c - 如何在复杂的 C 代码中处理多个参数选项