我猜你让这变得比它必须的更复杂。为了更好地理解,我假设当你说我需要将图片框(pictureBox11 到 pictureBox30)添加到数组中。你的意思是你的表单上有 30+ PictureBoxs,每个 @ 987654322@ 使用命名约定,每个都命名为“pictureBoxX”,其中“X”是 1,2,3…30,31。然后你想在表单上获得一组(连续的?)“图片框”以使其不可见。我希望这是正确的。
为了简单地使图片框不可见,我认为不需要数组。如果名称与“pictureBoxX”形式的字符串匹配,则只需遍历图片框并使其不可见。我使用IndexsAreValid 方法来验证开始和结束索引。它也用于此代码下方的数组实现代码中。
在没有数组的情况下使 PictureBox 不可见
private void SetPictureBoxesInvisible(int start, int end) {
int size = -1;
string targetString = "";
if (IndexsAreValid(start, end, out size)) {
for (int i = start; i < end + 1; i++) {
try {
targetString = "pictureBox" + i;
PictureBox target = (PictureBox)Controls.Find(targetString, true)[0];
if (target != null) {
target.Visible = false;
}
}
catch (IndexOutOfRangeException e) {
return;
}
}
}
}
如果您必须返回一个PictureBox 数组,那么下面的代码应该可以工作。
首先,要获得您想要的PictureBoxs 数组,您需要一个数组来存储它们。但首先你需要知道它有多大。从您发布的代码看来,您想要获取图片框 11-30 并将它们放入一个数组中。所以我们可以从这些数字中得到大小……即 30-11=19 +1 = 20。这就是你所需要的。只需创建数组并遍历所有图片框并获取图片框11-图片框30。完成后,我们可以使用该数组使这些“图片框”不可见。
我创建了一个类似于tryParse 的方法IsValidPic 来验证给定索引(1,2,3..30)是否有效。如果超出范围,我将忽略该值。这使您能够在所需的图片框不连续的情况下获取单个图片框。我使用了几个按钮来测试这些方法。
希望这会有所帮助。
private PictureBox[] GetPictureBoxes(int start, int end) {
int size = - 1;
if (IndexsAreValid(start, end, out size)) {
PictureBox curPic = null;
PictureBox[] allPics = new PictureBox[size];
int index = 0;
for (int i = start; i <= end; i++) {
if (IsValidPic(i, out curPic)) {
allPics[index] = curPic;
index++;
}
}
return allPics;
}
else {
return new PictureBox[0];
}
}
private Boolean IndexsAreValid(int start, int end, out int size) {
if (start < 1 || end < 1) {
size = -1;
return false;
}
if (start > end) {
size = -1;
return false;
}
size = end - start + 1;
return true;
}
private Boolean IsValidPic(int index, out PictureBox picture) {
string targetName = "pictureBox" + index;
try {
PictureBox target = (PictureBox)Controls.Find(targetName, true)[0];
if (target != null) {
picture = target;
return true;
}
picture = null;
return false;
}
catch (IndexOutOfRangeException e) {
picture = null;
return false;
}
}
private void ResetAll() {
foreach (PictureBox pb in this.Controls.OfType<PictureBox>()) {
pb.Visible = true;
}
}
private void button1_Click(object sender, EventArgs e) {
TurnInvisible(2, 3);
}
private void button3_Click(object sender, EventArgs e) {
TurnInvisible(11, 30);
}
private void button4_Click(object sender, EventArgs e) {
TurnInvisible(1,7);
}
private void TurnInvisible(int start, int end) {
PictureBox[] pictureBoxesToChange = GetPictureBoxes(start, end);
foreach (PictureBox pb in pictureBoxesToChange) {
if (pb != null)
pb.Visible = false;
}
}
private void button2_Click(object sender, EventArgs e) {
ResetAll();
}