C# .NET 列表声明。大小未知
我必须声明一个列表并在我的代码中使用它。每次运行代码时,我将添加到列表的元素数量都会有所不同。那么如何创建一个列表并向其动态添加元素而不需要在声明时指定其大小?
I have to declare a list and use it in my code.How ever the number of elements that i will add to list will vary during each time I run my code.So how can I create a list and add elements to it dynamically with out specifying its size during declaration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.Net 中的列表会在您添加内容时自动调整其大小。
List's in .Net will automatically resize themselves as you add to them.
您不必指定列表的边界(就像处理数组一样)。您可以继续调用 Add() 方法向列表中添加元素。您可以创建仅接受指定类型对象的通用列表和仅接受对象的非通用列表:
通用:
非通用:
后者可以采用任何对象对象的类型,但不是类型安全的。
You don't have to specify the bounds of a list (as you do with arrays). You can keep on calling Add() method to add elements in the list. You can create either a generic list which takes only specified types of objects and a non-generic list that only takes objects:
Generic:
Non-Generic:
The later can take any type of object but is not type-safe.
System.Collection 命名空间充满了可以动态收缩和扩展其大小的集合类,请参阅通用命名空间以了解最常用的类:http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
如果您有疑问,我建议您坚持使用列表你在做什么:
The System.Collection namespace is full of collection classes that can dynamically contract and expand its size, see the Generic namespace for the most used classes: http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
I recommend sticking with a List if you doubt what you are doing: