使用字符串 .NET 的名称变量 [英] Name Variable using string .NET

查看:37
本文介绍了使用字符串 .NET 的名称变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 .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";

现在我该怎么做才能让我的代码动态声明一个名为 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.

例如:在 javascript/jQuery 中,当我通过发出请求来获取 JSON 时,解释器会声明同名的变量/数组并为它们分配值.如果 {"var_name":"var_value"} 是一个 JSON 字符串,解释器将创建一个名为 var_name 的变量并将var_value"分配给它,例如 json_data_object.var_name.

推荐答案

不,你不能.C#变量都是静态声明的.

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

这篇关于使用字符串 .NET 的名称变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆