c# - 循环通过按钮单击 Xamarin 上的字符串
问题描述
private void Button_Clicked(object sender, EventArgs e)
{
string[] quotes = new string[3];
quotes[0] = "1st quote";
quotes[1] = "2nd quote";
quotes[2] = "3rd quote";
for (int i = 0; i < quotes.Length; i++)
{
label.Text = quotes[i];
}
}
这是我第一个使用 xamarin 的“测试”项目,我试图弄清楚如何在按钮单击时循环遍历字符串。此外,当某个“quotes[i]”存在时,它的值等于我的 XAML 文件中的 label.Text。我对何时可以使用 int vs string 感到困惑,因为这与 JS 不同。
解决方案
这里的问题是变量不是全局的,所以当用户停止点击按钮时,他们的进度会重置。
private int currentIndex = 0;
private void Button_Clicked(object sender, EventArgs e)
{
string[] quotes = new string[3];
quotes[0] = "1st quote";
quotes[1] = "2nd quote";
quotes[2] = "3rd quote";
label.Text = quotes[currentIndex];
currentIndex++;
if (currentIndex == 3){
currentIndex = 0
}
}
这个答案确保一旦用户点击了三次,它就不会像 RippStudwell 的答案那样使程序崩溃。
推荐阅读
- arrays - 为什么随机打乱的数组会重复
- arrays - 关于过滤/绘制numpy数组的问题
- git - 在 Cent 上安装 Gitlab
- javascript - 代码未按顺序执行(Firebase)。同步问题
- java - 在java中将一个列表转换为另一个列表
- r - R xts lag() 函数仅滞后 1 个位置
- c - 当我运行 Valgrind 时,我的代码中出现大小为 8 的无效写入错误
- html - 如何定位一个 div,在 100% 宽度的 body 中,左右空间相同?
- rust - PhantomData 在 Rust 中究竟是如何工作的?
- go - Golang 中的路由仅使用 stdlib