如何测试多个变量并在 C# if 语句中单独对它们进行操作?

for*_*fie 0 c# if-statement

我的 C# 程序中有一些基本代码,其中使用 3 个 if 语句。

if (leftIndex >= imageList.Count - 1)
{
    leftIndex = 0;
}
if (middleIndex >= imageList.Count - 1)
{
    middleIndex = 0;
}
if (rightIndex >= imageList.Count - 1)
{
    rightIndex = 0;
}
Run Code Online (Sandbox Code Playgroud)

这对于代码本身来说效果很好,但我想知道如何简化它以单独作用于每个代码,以防我有更多变量需要使用。

Som*_*ody 5

您可以使用带有 ref 参数的方法:

private void ModifyIndex(ref int index)
{
  if (index >= imageList.Count - 1)
  {
      index = 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

用法是

ModifyIndex(ref leftIndex);
ModifyIndex(ref middleIndex);
ModifyIndex(ref rightIndex);
Run Code Online (Sandbox Code Playgroud)