C#: Using a string variable to call and give names to other stuff
So I want to use a string variable to call or declare other stuff. For example: I write down "some_random_name" in a text box and then press a button that calls a function which declares a variable or object called "some_random_name". Another example:开发者_如何学C I have declared a variable from type integer called "a_variable". I write down this name in a text box and then I press a button that calls a function which shows me the value of "a_variable". The second example can also be done this way:
if (the_wanted_variable == "a_variable") show_value(a_variable);
But that's a different question.
I have found a solution... but I couldn't understand it. It was about Reflections. Maybe a need an easier to understand explanation how to do it (no matter how big it is).
Thanks!
Reflection is a way to examine/use the properties/methods of an object at runtime. Some explanations here:
C#: Can someone explain the practicalities of reflection?
Instead of creating different variables for each key/value pair entered by the user, you could store all key/value pairs in one Dictionary.
Reflection is an option; but if the needs of your program are very predictable you can avoid it for a potentially easier solution.
In the example you've given - if the user is presented with a textbox and they enter the name of a variable like 'MyTest1' and can press a button called 'Add 1' you could accomplish it with a key/value pair dictionary.
In other words - if the user enters text that they haven't entered before, you create a new integer value and set it's value to 0. If the user clicks on a button, it calls a predefined function on that value associated with that key. 'Add 1' to a newly created key would return '1'.
You can use a dictionary to store the variables.
Dictionary<string,string> Variables;
if you don't want strings, you can use a Dictionary<string, object>
but you have to be aware of the type to cast it when you click the button.
精彩评论