使用字符串.NET命名变量

我正在研究.NET中的反序列化类,我必须开发一个方法,它为我提供了一个存储在字符串中的变量名。

我有一个字符串,如:

string string_name = "this_is_going_to_be_var_name"; 

现在,我可以做什么,以便我的代码动态声明一个名为this_is_going_to_be_var_name的变量?

为了清理起来:将会有一个反序列化类,它将根据高级程序员/用户的意愿,声明与作为输入提供的字符串相同的变量及其PARENT TYPES。

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

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

您可以做的最好的事情是创建一个字典并使用键而不是变量名。

 // Replace object with your own type Dictionary myDictionary = new Dictionary(); 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"]); 

这是不可能的,变量名在编译时定义,而不是在运行时定义。 一种方法是创建一个字典或散列表来将字符串名称映射到对象,以实现您想要的排序。

不确定你的意思

我的代码动态地声明了一个名为 this_is_going_to_be_var_name 的变量

但PHP中explode的.Net版本是Split

 string[] zz = "this_is_going_to_be_var_name".Split('_'); 

我能想到的唯一一件事(我没有测试它,所以我不知道是否可能),是有一个类型为dynamic的对象,然后尝试使用reflection和InvokeMember在运行时设置字段( ),我可以给它一个机会,它可以工作,因为没有动态类型对象的validation。

更新:我用ExpendoObject测试它,InvokeMember似乎不起作用(至少没有使用默认的绑定器,但我没有使用DynamicObject测试它,尽管我没有给它很多工作机会你可能仍然试试看,你可以查看http://msdn.microsoft.com/en-us/library/ee461504.aspx如何使用DynamicObject。

看看动态添加属性到ExpandoObject ,它实质上描述了一个方法,其中动态对象被转换为IDictionary,然后您可以通过使用标准字典访问添加属性,而它们实际上获取对象的属性。

我通过使用ExpendoObject类型的动态对象在示例项目中测试它,然后我添加另一个使用类型IDictionary引用它的变量,然后我尝试在两者上设置和获取属性,如下例所示:

 dynamic test = new ExpandoObject(); //reference the object as a dictionary var asDictinary = test as IDictionary; //Test by setting it as property and get as a dictionary test.testObject = 123; Console.Write("Testing it by getting the value as if it was a dictionary"); Console.WriteLine(asDictinary["testObject"]); //Test by setting as dictionary and get as a property //NOTE: the command line input should be "input", or it will fail with an error Console.Write("Enter the varible name, "); Console.Write("note that for the example to work it should the word 'input':"); string variableName = Console.ReadLine(); Console.Write("Enter the varible value, it should be an integer: "); int variableValue = int.Parse(Console.ReadLine()); asDictinary.Add(variableName, variableValue); Console.WriteLine(test.input);//Provided that the command line input was "input" 

(但是在你的情况下,因为你无论如何都不能直接在代码中访问属性我没有看到它的需要你可能会直接使用一个字典,我不明白为什么你需要它们对象的属性,仅在您希望在编译时引用它们时才需要。

但也许我误解了你,你正在寻找一个动态变量,而不是动态属性[PHP使用$$语法提供的东西],如果是这种情况那么请注意,在c#中根本没有变量因为一切都封装在一个对象中)。

您还可以查看如何在C#中为类动态添加字段以获取更多答案。