How do I name variables dynamically in C#?

前端 未结 9 2125
悲哀的现实
悲哀的现实 2020-11-27 06:30

Is there a way to dynamically name variables?

What I need to do is take a list of variable names from an input file and create variables with those names. Is this p

相关标签:
9条回答
  • 2020-11-27 07:19

    Variable names should be known at compile time. If you intend to populate those names dynamically at runtime you could use a List<T>.

     var variables = List<Variable>();
     variables.Add(new Variable { Name = input1 });
     variables.Add(new Variable { Name = input2 });
     ...
    
    0 讨论(0)
  • 2020-11-27 07:24

    C# 4.0, using the dynamic objects:

    dynamic d = new ExpandoObject();
    ((IDictionary<string, object>)d)["MyProperty"] =  5;
    int val = d.MyProperty; // 5
    
    0 讨论(0)
  • 2020-11-27 07:29

    No, but you could use a Dictionary<string, Variable>, and then you can refer to each variable by its quoted name.

    0 讨论(0)
提交回复
热议问题