如何使用字符串在C#中的变量名 [英] How to use string as variable name in c#
问题描述
我有哪些属于类似值的视图状态:
am having a viewstate which pertains value like:
串温度;
的ViewState [临时] = dc.ColumnName.ToString();
这将返回工作日,如:周一,周二,周三
等
This returns weekdays like: Monday,tuesday,wednesday
etc
现在我在这里使用这个值:
Now am using this value here:
string a = "txt" + ViewState["temp"].ToString();
TextBox a = new TextBox();
但它给我的错误
无法隐式转换类型'System.Web.UI.WebControls.Textbox'到'字符串'
Cannot implicitly convert type 'System.Web.UI.WebControls.Textbox' to 'string'
我想文本框的变量名称,如 txtmonday,txttuesday
动态。
有没有办法,我可以指定变量名称的任何方式?
I want textbox variable name like txtmonday,txttuesday
dynamically.
Is there any way that I can assign variable name???
推荐答案
没有,你不能。至少在没有反映,你不应该在这里使用反射。在C#中的变量是一个编译时的概念。 (即使是与反思,它会只对下地干活,不为局部变量。)
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.)
如果你想有一个的集的值,使用集合...例如一个列表< T>
或词典< TKEY的,TValue>
。因此,例如,你可以有一个列表<文本框>
(这是按索引访问)或词典<字符串文本框>
这是由字符串键(星期一
,星期二
或你想要的)访问。
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.
这篇关于如何使用字符串在C#中的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!