[英]How to get the variable with its name in C#
Want to use a variable based on its name. 想要根据其名称使用变量。 It is hard to describe.
很难描述。 Here is the example
这是例子
var sections = new[] { "Personnel", "General", "Medical" };
foreach (var s in sections)
{
// want to retrieve the variable "lblPersonnel"
(Label)Type.GetType(string.Format("lbl{0}", s)).Text = "Test";
}
so that we don't have to : 这样我们就不必:
lblPersonnel.Text = "Test";
lblGeneral.Text = "Test";
lblMedical.Text = "Test";
So, is it possible for this kind of "reflection"? 那么,这种“反射”可能吗?
Type.GetType
expects a fully-qualified type name but you are trying to pass it name of the variable.And also it returns a Type
instance so you can't cast it to Label
.It seems you are confused about types,instances and variables. Type.GetType
需要一个完全限定的类型名,但是您尝试传递给它一个变量名。它还会返回一个Type
实例,因此您不能将其强制转换为Label
似乎您对类型,实例和变量感到困惑。 If you have labels and you want to access them you can use Controls
collection of your Form
. 如果您有标签并且要访问它们,则可以使用
Form
Controls
集合。
foreach (var s in sections)
{
var name = string.Format("lbl{0}", s);
if(this.Controls.ContainsKey(name))
{
var currentLabel = this.Controls[name] as Label;
if(currentLabel != null) currentLabel.Text = "Test";
}
}
Edit: If you are devoloping an ASP.NET
project then you can use FindControl
method to get your labels by name: 编辑:如果您正在开发一个
ASP.NET
项目,则可以使用FindControl
方法按名称获取标签:
foreach (var s in sections)
{
var name = string.Format("lbl{0}", s);
var currentLabel = FindControl(name) as Label;
if(currentLabel != null) currentLabel.Text = "Test";
}
Why not just get the label using Controls
? 为什么不仅仅使用
Controls
获得标签?
var sections = new [] {"Personnel", "General", "Medical"};
foreach (var s in sections)
{
// want to retrieve the variable "lblPersonnel"
((Label)(Controls["lbl" + s])).Text = "Test";
}
foreach (var s in sections)
{
string name = string.Format("lbl{0}", s);
FieldInfo fi = typeof(Form1).GetField(name);
Label l = (Label)(fi.GetValue(this));
l.Text = "Test";
}
This is assuming the Label
s are public fields. 假设
Label
是公共字段。 If they are properties - use GetProperty
, if they are private fields, use: 如果它们是属性,请使用
GetProperty
;如果它们是私有字段,请使用:
GetField(name, BindingFlags.NonPublic | BindingFlags.Instance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.