简体   繁体   English

声明名为字符串+整数值的变量

[英]declare variable named as string+integer value

I want to add tabpages to tabcontrol1, and need to have tabpages created dynamically 我想将标签页添加到tabcontrol1,并且需要动态创建标签页

 int a=10;
 TabPage tabpage"+a+" = new TabPage();

How can i achieve this : 我怎样才能做到这一点:

tabpage10
tabpage12
tabpage13

created dynamically 动态创建

You can't, and you shouldn't try to. 您不能,也不应尝试。 Instead, either have an array or list (if your numbers are all positive, effectively starting near 0) or a Dictionary<int, TabPage> for a more general mapping. 相反,可以使用数组或列表(如果您的数字都是正数,则实际上从0开始)或使用Dictionary<int, TabPage>进行更一般的映射。

Whenever you find you have a collection of values, you should reach for a collection type - rather than a lot of different variables which happen to have names starting with a common prefix. 每当发现有值的集合时,都应该获取一个集合类型-而不是很多其他的变量碰巧都具有以公共前缀开头的名称。

You can't dynamically generate variable names - and nor would you want to. 您不能动态生成变量名,也不想。 Instead, consider adding the tab page to a collection. 相反,请考虑将标签页添加到集合中。

List<TabPage> tabs = new List<TabPage>();
tabs.Add(new TabPage()); // 0
tabs.Add(new TabPage()); // 1
tabs.Add(new TabPage()); // 2

If you're in winforms: 如果您使用的是Winforms:

int a = 10;
tabcontrol1.TabPages.Add(new TabPage("text") { Name = "tabpage" + a });
a++;

Then to access 然后访问

var page = tabcontrol1.TabPages[0];

or by name 或按名称

var page = tabcontrol1.TabPages["tabpage" + a];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM