How to add an interator number to a variable name?

南笙酒味 提交于 2020-01-06 06:58:16

问题


In my program i'm currently working on programmatically adding a variety of form objects in C#. For example i'm trying to create a certain group of panels, which contain the data I wish to show. When loading the form I have a file which contains all of the data I wish to load in, the loading itself works fine but when loading I need to create a variety of form labels, panels and images to display all of the necessary data and as such I need to make these panels and labels all with a seperate name, but programmatically.

for (int i=0; i<fileLength; i++)
{
    Panel pnl = New Panel();
    pnl.Name = "pnl1"+i;
    //Set the other properties here
}

What i'm trying to do if use an iterator to append the current iteration to the end of the name. Am I going the right way about it? Or should I be doing a different method?


回答1:


You cannot change variable/object name at runtime. If you want to write code against the object than you need to keep a reference to it. In your case you have changed the Name property of Panel but still you have to use it as pnl, not as pnl0 or pnl1.

The other way for doing this would be to use a Dictionary with key as the name as you assign and value as the object itself. This will help you in accessing your controls using its name that you have assigned to it.

Dictionary<string, Panel> panels = new Dictionary<string, Panel>();
for (i = 0; i <= 10; i++) {
    Panel pnl = new Panel();
    panels.Add("pnl" + i.ToString(), pnl);
}
//write code against panels
panels("pnl0").Width = 100;

For accessing within loop:

foreach (string pnlName in panels.Keys) {
    panels(pnlName).Visible = true;
}

for (i = 0; i <= 10; i++) {
    panels("pnl" + i).Visible = true;
}


来源:https://stackoverflow.com/questions/32221859/how-to-add-an-interator-number-to-a-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!