我试图编写一段代码来设置我的表单中的92个图片框的图像。我不想写92次相同的代码,所以我想知道这是否可以做得更快。我的代码是:我该如何重用一段代码来编辑多个图片框
public void drawRoute()
{
if (route1.line_00_R == null)
{
this.tabMap.Controls.Remove(this.line_00_R);
}
else if (route1.line_00_R == "Blue")
{
this.tabMap.Controls.Add(this.line_00_R);
this.line_00_R.Image = global::MijnenvegerController.Properties.Resources.Blue;
}
else if (route1.line_00_R == "Red")
{
this.tabMap.Controls.Add(this.line_00_R);
this.line_00_R.Image = global::MijnenvegerController.Properties.Resources.Red;
}
}
我希望这样的事情是可能的:
public void drawRoute()
{
for (//all values of {0})
{
if (route1.{0} == null)
{
this.tabMap.Controls.Remove(this.{0});
}
else
{
{1} = route1.{0}; // string that is the same as the name of the resource
this.tabMap.Controls.Add(this.{0});
this.{0}.Image = global::MijnenvegerController.Properties.Resources.{1};
}
}
}
其中{0}和{1}都是某种形式的占位符或变量。
希望有人能帮助我。我只是从本周开始使用C#,所以我认为这不是一个愚蠢的问题。预先感谢所有帮助!
编辑
我找到了,我想我可以使用,但我不知道如何实现它:
public Control[] Find( string key, bool searchAllChildren )
Control.ControlCollection.Find Method (http://msdn.microsoft.com)
我知道我能做到这一点像现在。但我已经使用Disigner制作了所有不同的PictureBox。我现在使用此代码在一个非常肮脏的方式 '解决':
` 公共无效drawRoute(){ drawRoad(route1.line_00_R,this.line_00_R); drawRoad(route1.line_00_U,this.line_00_U); 012RdrawRoad(route1.line_01_D,this.line_01_D); 012RdrawRoad(route1.line_01_R,this.line_01_R);
//等等92次!
drawRoad(route1.line_6, this.line_6);
drawRoad(route1.line_7, this.line_7);
drawRoad(route1.line_8, this.line_8);
drawRoad(route1.line_9, this.line_9);
drawRoad(route1.line_10, this.line_10);
drawRoad(route1.line_11, this.line_11);
drawRoad(route1.line_12, this.line_12);
}
public void drawRoad(string color, PictureBox control)
{
if (color == null)
{
this.tabMap.Controls.Remove(control);
}
else if (color.Equals("Blue"))
{
this.tabMap.Controls.Add(control);
control.Image = global::MijnenvegerController.Properties.Resources.Blue;
}
else if (color.Equals("DarkRed"))
{
this.tabMap.Controls.Add(control);
control.Image = global::MijnenvegerController.Properties.Resources.DarkRed;
}
else if (color.Equals("Indigo"))
{
this.tabMap.Controls.Add(control);
control.Image = global::MijnenvegerController.Properties.Resources.Indigo;
}
else if (color.Equals("GreyBlue"))
{
this.tabMap.Controls.Add(control);
control.Image = global::MijnenvegerController.Properties.Resources.GreyBlue;
}
else if (color.Equals("Gold"))
{
this.tabMap.Controls.Add(control);
control.Image = global::MijnenvegerController.Properties.Resources.Gold;
}
else if (color.Equals("Orange"))
{
this.tabMap.Controls.Add(control);
control.Image = global::MijnenvegerController.Properties.Resources.Orange;
}
}
`
如果你正在学习,重构可能会比肮脏的方式更好。最终它会为你节省很多工作。 – 2011-03-30 20:16:15
谢谢,这很有帮助,但我正在学习Electrical Engeneering,这只是为我们制作的地雷探测机器人制作一个无线控制界面。我们应该从命令行(C语言)来控制它,但是我想让它好一点。学习C#不是主要目标。 感谢您的帮助。 Erik – 2011-03-31 21:28:12