简体   繁体   中英

C# How can I used a string to reference a pre-existing variable by the same name?

I have a textfile and on each line is a single word followed by specific values

For example:

texture_menu_label_1 = 0 0 512 512

What I want to do is read that text in and basically convert it to the following commmand:

texture_menu_label_1 = new int[]{0, 0, 512, 512};

Parsing the line and extracting the integer values for the constructor is trivial, but im wondering if there is anyway to use the "texture_menu_label_1" String from the file to reference a pre-existing variable by the same name...

Is there anyway to do this without manually constructing a lookup table?

You really don't want to do this. I know you think you do, I remember when I was learning how to program and I thought the same thing, but really, you don't.

There are better ways to store a collection values, in your case, this would be a multi-dimensional array (or a List<List<int>> ). If not that, then perhaps a hash table ( Dictionary<string,int[]> ).

Better yet, if this data is 'regular' and logically connected, create your own custom type and maintain a collection of those. You really don't want to go down the road of tying your logic to the names of your variables... very messy.

That data looks like a rectangle. Why not just maintain a Dictionary<string,Rectangle> ?

var dict = new Dictionary<string, Rectangle>();
dict.Add("some_name", new Rectangle(0, 0, 512, 512));
// ... later
var rect = dict["some_name"];  // get the rectangle that maps to "some_name"

Before you try to implement an answer please consider why you are doing this, and whether there may be a better solution.

I recommend using a Dictionary to store the data by name as strings.

dataDictionary["texture_menu_label_1"] = new int[] { ... };

Another approach is to use a separate class with fields, since fields can be accessed by name. You may experience performance issues though, and it's definitely not an optimal solution.

class Data
{
    public int[] texture_menu_label_1;
    ...
}

You can use reflection to set the field value. Something like this:

typeof(Data).GetField("texture_menu_label_1").SetValue(data, new int [] { ... });

Use a HashTable (Dictionary for generics) or similar. The key would be the string (texture_menu_label_1) and the value would be the array.

What if you wrap it up in a struct?

struct TextureMenu
{
  string MenuString;
  int[] Values;
}

Then, instead of dealing directly with either type, you just deal with the struct.

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