How to use string as variable name in c#

后端 未结 2 540
孤街浪徒
孤街浪徒 2020-12-22 13:02

am having a viewstate which pertains value like:

string temp; ViewState[\"temp\"] = dc.ColumnName.ToString();

This returns weekdays like:

相关标签:
2条回答
  • 2020-12-22 13:07

    You can not declare objects at runtime they way you art trying. You can store the week days in array / List<T> starting Monday at index 0 and Sunday at index 6, You can give id of element with the string name you want.

    List<TextBox> weekList = new List<TextBox>();
    weekList.Add(new TextBox());
    weekList[0].ID  =  "txt" + ViewState["temp"].ToString();
    
    0 讨论(0)
  • 2020-12-22 13:18

    No, you can't. At least not without reflection, and you shouldn't be using reflection here. Variables in C# are a compile-time concept. (Even with reflection, it'll only work for fields, not for local variables.)

    If you want a collection of values, use a collection... e.g. a List<T> or a Dictionary<TKey, TValue>. So for example, you could have a List<TextBox> (which is accessed by index) or a Dictionary<string, TextBox> which is accessed by string key ("monday", "tuesday" or whatever you want).

    If you're only actually creating a single TextBox, what does it matter what the variable name is? Just use:

    TextBox textBox = new TextBox();
    // Do appropriate things with the TextBox, possibly using ViewState
    

    The variable name just gives you a way of referring to the variable. That's all it's there for. The object you create doesn't know anything about which variables (if any) contain references to it.

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