c# - 如何在命令的 for 循环中使用变量?(C#)
问题描述
所以我有一个按钮矩阵,从a1f到a10f,从a到j,所以a1f在左上角,j10在右下角。
我想要这样的事情:
for (i = 1; i < 11; i++)
{
a{i}f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b{i}f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a{i}f.Enabled = false;
a{i}f.Tag = "playerShip";
b{i}f.Enabled = false;
b{i}f.Tag = "playerShip";
}
所以第一个循环是:
a1f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b1f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a1f.Enabled = false;
a1f.Tag = "playerShip";
b1f.Enabled = false;
b1f.Tag = "playerShip";
第二个是:
a2f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b2f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a2f.Enabled = false;
a2f.Tag = "playerShip";
b2f.Enabled = false;
b2f.Tag = "playerShip";
等等..
a{i}f 或 a[i]f 不起作用。
解决方案
如果您无法迭代控件,则可以将它们存储在临时数组中。
但是您可能会更好地通过生成控件来做。这可能是改进的下一个层次。现在,你可以试试这个:
例如:
// create arrays which contains the controls.
var aShips = new [] { a1f, a2f, a3f, a4f, a5f, a6f, a7f, a8f, a9f, a10f };
var bShips = new [] { b1f, b2f, b3f, b4f, b5f, b6f, b7f, b8f, b9f, b10f };
// notice the 0 and the < 10, because arrays are zero-indexed
for (i = 0; i < 10; i++)
{
// now you can access them via the array.
aShips[i].BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
aShips[i].Enabled = false;
aShips[i].Tag = "playerShip";
bShips[i].BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
bShips[i].Enabled = false;
bShips[i].Tag = "playerShip";
}
推荐阅读
- netsuite - Netsuite 已保存搜索检查相关记录中的字段
- django - Update view not displaying data
- python - 在 Python 中实现 peek() 方法时处理空堆栈的正确方法
- java - Can you "cast" a PCollection
to a PCollection to avoid deserialization? - java - If you have set spring.cloud.config.server.bootstrap=true, you need to use a composite configuration
- javascript - Typescript passing rest props to React component throws does not exist
- flutter - Scalling Image of a Carousel on Dragdown in Flutter
- flutter - Flutter:如何像 WhatsApp 一样在 Google Drive 上备份用户数据?
- c++ - Dynamic verb for Windows shell context/shortcut menu extension
- html - Show base64-image from WebApi on HTML-Page