简体   繁体   中英

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)
{
labelXXX.Show();
}

But with Variable 's value instead of XXX . Is it possible?

You don't need reflection, you can use

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.

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