我的 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)
这对于代码本身来说效果很好,但我想知道如何简化它以单独作用于每个代码,以防我有更多变量需要使用。
您可以使用带有 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)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |