private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter++ % Words.wordsArray.Length];
}
[编辑]
好的,这是与 user1397396 评论相关的编辑。我不确定我是否正确理解您,但您可能对负值模数有疑问。例如:
int counter = 0;
int mod = 4;
counter--; // counter is -1 after this line is executed
int result = counter % mod; // result is -1
result = (counter + mod) % mod; // result is now 3 as desired
以下是我将如何实现这些 Next 和 Previous 按钮。
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter % Words.wordsArray.Length];
counter++; // put ++ operator in new line to avoid confusion
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
int wordCount = Words.wordsArray.Length;
// add wordCount before applying modulus (%) to avoid negative results
// -1 % 5 = -1; -2 % 5 = -2; -6 % 5 = -1 etc
// negative values would cause exception when accessing array
counter = ((counter - 1) + wordCount) % wordCount;
enWordTextBlock.Text = Words.wordsArray[counter];
}
例如,此代码将导致按 Next、Previous、Next 为您提供:“one”、“four”、“one”。
更好的解决方案是使用如下方法(或内联代码):
private static int GetPositiveIntModulus(int value, int mod)
{
return ((value % mod) + mod) % mod;
}
对于任何值,它都会给你一个积极的结果,即使是value < -mod
. 所以你可以这样写上面的代码:
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
// uncomment this to ensure valid counter
// if it is changed somewhere else in the program
//counter = GetPositiveIntModulus(counter, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
counter = GetPositiveIntModulus(counter + 1, Words.wordsArray.Length);
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
counter = GetPositiveIntModulus(counter - 1, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
}