是否可以根据用户输入动态命名变量? [英] Is it possible to dynamically name variables based off user input?

查看:56
本文介绍了是否可以根据用户输入动态命名变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用C#开发一个项目,该项目要求用户创建所需数量的类实例.我已经考虑过两种不同的解决方法.

I've recently started working on a project in C# that requires the user to create as many instances of a class as they'd like. I've thought about two different ways to go about this.

1:使用字符串数组列表,其中包含该类保存的信息.我的意思是说,当他们创建类的实例时,数据将进入列表,以便我可以重复使用相同的变量名.

1: Use a list of string arrays that contains the information held by the class. By this I mean when they create an instance of the class the data goes to a list so that I can re-use the same variable name.

// Initiating the class
dataSet1D currDataSet = new dataSet1D();
dataSet1D.name = txtName.Text;
dataSet1.length = Int32.Parse(txtIndex.Text);

// Creating the list of arrays
List<string[]> arrayList = new List<string[]>();
string[] strArray = new string[2];
strArray[0] = "name";
strArray[1] = "lengthAsString";
arrayList.Add(strArray);

(那只是一些快速的模拟代码,我显然会在实际项目中使用更好的变量名)

(That was just some quick mock-up code, I'll obviously use better variable names on my actual project)

2:我可以使用动态命名的变量如果他们输入想要的名称,我可以为其命名.

2: I could use dynamically named variables If they enter what they want as a name, I can name the instance that.

dataSet1D <dynamically named variable name> = new dataSet1D();

推荐答案

您可以创建一个字典,将变量"的名称映射到实际的calss实例,也可以创建一个包含所有实例及其实例的列表.在这种情况下,使用索引而不是名称.

You can creat a dictionary which maps the name of the "variable" to the actual calss instance, or you can create a List which has all your instances and they have an index in this case rather than a name.

这篇关于是否可以根据用户输入动态命名变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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