Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm working on a deserialization class in .NET, I have to develop a method that provides to me with a variable name that is stored in a string.

I have a string such as:

string string_name = "this_is_going_to_be_var_name";

Now what can I do so that my code dynamically declares a variable named this_is_going_to_be_var_name?

So to clear things up: There will be a deserialization class that will declare variables of the same names as strings provided as input with their PARENT TYPES as per wish of the Higher Level Programmer/User.

For Example: In javascript/jQuery, when I fetch JSON by making a request, the interpreter declares variable(s)/array(s) of the same name and assigns values to them. If {"var_name":"var_value"} is a JSON string, the interpreter will create a variable named var_name and will assign "var_value" to it such as json_data_object.var_name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
117 views
Welcome To Ask or Share your Answers For Others

1 Answer

No you can't. C# variables are all statically declared.

The best thing you can do is create a dictionary and use keys instead of variable names.

// Replace object with your own type
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
myDictionary.Add("this_is_going_to_be_var_name", value_of_the_variable);
// ...
// This is equivalent to foo($this_is_going_to_be_var_name) in PHP
foo(myDictionary["this_is_going_to_be_var_name"]); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...