简体   繁体   中英

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. If you have labels and you want to access them you can use Controls collection of your Form .

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:

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 ?

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. If they are properties - use GetProperty , if they are private fields, use:

 GetField(name, BindingFlags.NonPublic | BindingFlags.Instance); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM