I am trying to create some variables dynamically from a textbox or xml-script. So far I am making a 开发者_开发百科program to create scripts for the server application. In that script I want to use variables which you can create in a form by entering a name and the type and maybe the scope.
So, if I enter Counter as an Int it has to create a variable called Counter.
Like: int Counter = 0;
Simple way would be to use a dictionary:
Dictionary<string, object> dynamicVars = new Dictionary<string, object>();
You might have to wrap that in a class and add type checking for the objects in the dictionary, but the dictionary will give you the ability to create and add any type of name/value pair.
Creating a variable based on input isn't a good idea, it's a huge amount of work and required a dynamic runtime. A much more simple approach is to use a Dictionary<TKey,TValue>
, and use the text in the TextBox as a key.
Dictionary<String,Type> dynamicVars = new Dictionary<String,Type>();
dynamicVars.Add("Counter",typeof(int));
The above code segment would do it. But I cannot fathom why you would need such a thing ?
Just Curious...
精彩评论