开发者

How to add a variable into object's name in C#?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜