It is possible to create something like that:
int[] array = new int[3]{1,2开发者_运维百科,3};
Button "btn"+array[0] = new Button();
You can easily create an array of Button
instances, but you won't be able to access them by name at compile-time; since the name would be generated at runtime, you would have to store the keys at runtime as well.
The closest thing you could do is populate an implementation of IDictionary<string, Button>
, like so:
int[] array = new int[3] { 1, 2, 3 };
IDictionary<string, Button> buttons =
array.ToDictionary(i => "btn" + i, i => new Button());
Of course, accessing the controls through the keys (i.e. btn1
, btn2
, btn3
) is the problem you have to overcome (I assume you'd store these somewhere, and access them later).
Based on your comment, It should be noted that the names that you are referring to are not significant to the form or the framework, they are only significant to you. You don't have to use an IDictionary
if you don't wish, it's just if you wish to do further work on them later (depending on your needs).
This is not possible - you could use a dictionary instead:
var myButtons = new Dictionary<string,Button>();
myButtons.Add( "btn"+array[0], new Button());
var firstButton = myButtons["btn1"];
What you asked is not directly possible, but I think there is an answer for what you're actually looking for:
Suppose you've got any IEnumerable<int>
like your own array:
Dictionary<int, Buttton> buttons = new Dictionary<int, Button>;
foreach (int key in array)
{
Button b = new Button();
b.Text = key.ToString();
buttons.Add(key, b);
}
now you can easily use the buttons like this: buttons[1]
精彩评论