Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c# - Name Variable using string .NET

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

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

1 Reply

0 votes
by (71.8m points)

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"]); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...