【发布时间】:2021-12-03 15:35:30
【问题描述】:
嘿,我的情况是,我有一个 for 循环来做一些事情,我想编写一行代码,要么调用一个函数,传入一个由 for 循环索引索引的数组,要么运行一个(不是array) 变量,我知道我可以通过在 for 循环中放置一个 if 语句来做到这一点,但我会一遍又一遍地重复相同的 if 语句以获得相同的结果。那么有没有一种好方法可以在 for 循环之前运行 if 语句,并且该 if 语句的结果运行相同的 for 循环,但是一个调用传入数组或变量?
代码示例
for (int i = 0; i < CurrentVerticalList.Count; i++)
{
GuiGeneral CGroup = CurrentVerticalList[i];
CGroup.ResizeUsingStandard(ForcedResize[i]); //I want the condition before the for
//loop to have ForcedResize[i] here if
//true and another variable here of the
//same type but not an array if false.
for (int j = 0; j < 2; j++)
{
GlobalListIndex[j]++;
}
CGroup.MoveElementTo(CCoord, false);
CCoord.y += CGroup.ElementRect.WidthHeight.y;
}
【问题讨论】:
-
CGroup.ResizeUsingStandard(condition ? ForcedResize[i] : othervar)? -
不是每次循环时都检查条件还是只检查一次条件?
-
这可能会有所帮助Dynamic Array
-
它每次都会检查条件。如果该值永远不会改变,请在循环之前将该值捕获到
bool变量中,然后使用该变量 - 这很便宜 -
您要设置什么样的条件?每个元素都是随机的吗?循环的每个元素都不同吗?还是在循环结束之前条件的值不会改变?
标签: c# loops if-statement optimization