Troubles with dynamic and immutable arrays of control
In WPF C#, in code behind, I have to dynamically create an Array of Canvas (each Canvas also Children controls like Label, TextBox, Button etc.)
Canvas[] cv = new Canvas[myInt];
Label[] l = new Label[myInt];
TextBox[] tb = new TextBox[myInt];
...
Canvas.Children.Add(...);
Each of the Canvas can be dynamically added or removed. The issue is I have to give the Canvas array a length, and if one of the Canvas is removed the index will still remain and the afterwards elements cannot be pushed u开发者_运维百科pward. If later on I add new Canvases, the new Canvas may have a possibility to go out of range, unless I instantiate a very large Array from the beginning.
Is there a better solution to that? Would ArrayList, or List or what else?
This seems obvious but since you do not know in advance how many elements you have to store you should use a List<Canvas>
, List<Label>
etc. then you can use the methods list.Add()
and list.Remove()
.
Don't use ArrayList, you want your data strongly typed and be able to add and remove items dynamically - so List<T>
would fit the bill.
精彩评论