如何将变量名添加到变量名? [英] How to add an interator number to a variable name?

查看:274
本文介绍了如何将变量名添加到变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我目前正在以编程方式在C#中添加各种表单对象。例如,我正在尝试创建一组特定的面板,其中包含我希望显示的数据。加载表单时,我有一个文件,其中包含我要加载的所有数据,加载本身工作正常,但加载时我需要创建各种表单标签,面板和图像来显示所有必要的数据,如所以我需要使用单独的名称制作这些面板和标签,但需要以编程方式。

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?

推荐答案

您无法在运行时更改变量/对象名称。如果您想针对对象编写代码而不是需要保留对它的引用。在您的情况下,您更改了 Panel 名称属性,但仍然必须将其用作 pnl ,而不是 pnl0 pnl1

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.

执行此操作的另一种方法是使用 Dictionary ,并将key作为您指定的名称,并将值作为对象本身。这将帮助您使用已分配给它的名称访问控件。

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;

在循环内访问:

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

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

这篇关于如何将变量名添加到变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆