简体   繁体   中英

Is it possible to dynamically name variables based off user input?

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: 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: 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实例,也可以创建一个包含所有实例的List,在这种情况下,它们具有索引而不是名称。

If you need lots of instances of 1 class, you can just have a list of that class. Like this:

class MyClass
{
   public string Name {set;get;}
   // property2 , etc
}

var myList = new List<MyClass>();
myList.Add(new MyClass());

Other than this, I have to mention that variable names has nothing to do with the run-time. when you build your code, they will all change to pointers to space that contains the data.

Variable name is only a handler for programmers to let them work with their objects

You could create add a string property to the class which would hold the name the user specifies for each object. Then, as a new instance of each object is created, add it to a List as others have suggested. Finally when you need to access an instance by the user defined name, use a LINQ expression to retrieve it.

public class MyClass
{
    public string UserDefinedName { get; set; }
    public int Length { get; set; }
    ... Other member variables
}

public List<MyClass> UserCreatedObjects { get; set;}

Then to get an instance which was named, say "my_object_1" use LINQ:

var theInstance = UserCreatedObjects.Where(o => o.UserDefinedName == "my_object_1").FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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