C#处理数组与C或C的处理方式大不相同.它将它们视为一件事物的对象,尽管它们具有固定的大小.所以我对C#中的数组有一些疑问:
>如果我创建一个数组new int [10]将保证Length属性为10或C#尝试调整数组大小,如果我接近填充它?
>如果我需要调整数组大小,我是否必须创建一个更大的新数组,然后复制数组中的每个元素,或者我可以简单地添加更多空间而不复制元素.
编辑:看起来你可以使用Array.Copy复制数组.
> C#中的List集合看起来像一个动态大小的数组(可能是数组和链表之间的混合).如果我使用List而不是数组,我可以控制它的大小吗? (即强制它为长度10,如果我需要更多空间,则将其大小设置为20)
If I create an array new int[10] will the Length property be guaranteed to be 10 or does C# try and resize the array if I get close to filling it up?
它将是10.总是10.
If I need to resize the array,do I have to create a new one with a larger size and then copy over each element in the array,or can I simply add more space without copying the elements over.
您需要调整大小并复制.有一些辅助方法可以让这更容易,比如Array.Resize
– 但不要误以为它正在创建一个新数组并使用Array.Copy将所有内容放在那里.如果您需要可调整大小的集合,请使用List< T>.
The List collection in C# seems like a dynamically sized array (maybe a mix between arrays and linked lists). If I use a List instead of an array,can I control its size? (i.e. force it to be length 10,then set its size to 20 if I need more space).
尺寸自动控制.它会在需要时增长.有一个构造函数重载来接受初始大小.在内部,它还使用在需要时调整大小的数组.什么时候填满;它以当前容量的两倍增长,并复制列表中新底层数组中的所有内容.但所有这些魔力都发生在幕后.如果要手动调整List< T>的内部数组,请将Capacity属性设置为项目数.