質問

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

 GetField(name, BindingFlags.NonPublic | BindingFlags.Instance); 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top