Let's say I want a function like this:
private void ShowLabel(byte Variable)
{
la开发者_运维技巧belXXX.Show();
}
But with Variable's value instead of XXX. Is it possible?
You don't need reflection, you can use
- Windows Forms:
Controls.Find("label" + Variable.ToString())
- ASP.NET:
FindControl("label" + Variable.ToString())
- WPF:
FindName("label" + Variable.ToString())
But using a Dictionary<byte, Label>
, as suggested by CodeInChaos, would be preferable.
you could create an array of the Labels and use the value of Variable as the index to that array. But you question is pretty vague. Could you give more info on why you need to do this?
While you can do it with reflection, it smells. If you have many labels which are only distinguished by a number, perhaps create them at runtime and put them in List or dictionary, so you can look them up from the ID.
You could iterate over all the children of the parent control, compare their name to the name you want to find the control you want. But that has a bad smell.
精彩评论