[英]Looking for a more elegant DO WHILE solution
So I have some code centered around a do while loop. 所以我有一些以do while循环为中心的代码。
string token;
var count = 0;
var checkDataLength= data.Length == 16;
do
{
count = 0;
token = GenerateToken(data, start, end);
if (checkDataLength)
{
if (Mod120Check(token))
{
count += 1;
}
}
if (IsCompliant(token))
{
count += 1;
}
}
while (count > 0);
return token;
Basically, I am generating a token and for this token to be valid, has to FAIL the Mod120Check and the IsCompliant check. 基本上,我正在生成一个令牌,并且为了使此令牌有效,必须将Mod120Check和IsCompliant检查失败。 I cannot change how those methods return the data. 我无法改变这些方法返回数据的方式。
While the above code works, I feel that its ugly and I was wondering if anyone had a better way of doing it? 虽然上面的代码有效,但我觉得它很难看,我想知道是否有人有更好的方法吗?
Thanks 谢谢
Try this: 试试这个:
do
{
token = GenerateToken(data, start, end);
}
while (checkDataLength && Mod120Check(token) || IsCompliant(token))
Just moving your conditions to the while
. 只是将你的条件转移到while
。
(!) Notice that IsCompliant(token)
will only be called if checkDataLength && Mod120Check(token)
states false
. (!)注意IsCompliant(token)
如果将只能被称为checkDataLength && Mod120Check(token)
指出false
。 It shouldn't cause any colateral effects, but it could, depending on what your IsCompliant
method does. 它不应该导致任何附带效果,但它可能会取决于您的IsCompliant
方法的作用。
You're right, it is ugly. 你是对的,很难看。 You are using count
in an unexpected way (it gets reset to zero at the top of every loop, and can go positive for two different reasons). 您正以意想不到的方式使用count
(它在每个循环的顶部重置为零,并且由于两个不同的原因可以变为正数)。 When I see count
, I expect something to start at zero and count up (or start high and count done). 当我看到count
,我希望某些东西从零开始并计数(或开始高位并完成计数)。 Try this instead: 试试这个:
var count = 0;
改变var count = 0;
to var goodEnough = false;
to var goodEnough = false;
up at the top 在顶部 count = 0;
删除count = 0;
statement 声明 count += 1;
改变两个count += 1;
statements to goodEnough = true;
陈述到goodEnough = true;
while (count > 0);
改变while (count > 0);
to while (!goodEnough);
到了while (!goodEnough);
This emphasizes that you are starting in a "not good enough" state, and you will loop until some condition makes it good enough to continue past the loop. 这强调你开始处于“不够好”状态,并且你将循环直到某些条件使其足够好以继续经过循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.