迁移到.NET 2.0+之后,有没有理由继续使用systems.Collections命名空间(除了维护遗留代码)呢?泛型名称空间是否应该始终使用?泛型和System.Collections
8
A
回答
12
大多数情况下,泛型集合的执行速度会比非泛型集合的速度快,并为您提供强类型集合的好处。在比较System.Collections中和System.Collections.Generic可用的集合,你会得到下面的“移民”:
Non-Generic Generic Equivalent ------------------------------------------------------------ ArrayList List<T> BitArray N/A CaseInsensitiveComparer N/A CollectionBase Collection<T> Comparer Comparer<T> DictionaryBase Dictionary<TKey,TValue> Hashtable Dictionary<TKey,TValue> Queue Queue<T> ReadOnlyCollectionBase ReadOnlyCollection<T> SortedList SortedList<TKey,TValue> Stack Stack<T> DictionaryEntry KeyValuePair<TKey,TValue> ICollection N/A (use IEnumerable<T> or anything that extends it) IComparer IComparer<T> IDictionary IDictionary<TKey,TValue> IEnumerable IEnumerable<T> IEnumerator IEnumerator<T> IEqualityComparer IEqualityComparer<T> IList IList<T>
ICollection的是不变的(没有成员来更改集合的内容),而ICollection的<牛逼>是可变的。这使得名称相似的接口仅在ICollection和IEnumerable <T>相差很小。
从这个列表中,唯一没有泛型类的非泛型类是BitArray和CaseInsensitiveComparer。
0
在某些情况下,通用容器的性能比旧的要好。在任何情况下,他们至少应该表现得和旧表现一样。他们帮助捕捉编程错误。这是一个更有用的抽象和更好的性能的罕见组合,所以没有太多的理由来避免它们。只有当你被一个蹩脚的图书馆强迫时,你必须使用那些在泛型之前编写的图书馆。
0
我看到了一个来自C#团队的Anders Hejlsberg的采访,他被问到是否有任何他对以前版本的.net感到遗憾。在asp.net 1.0中没有泛型是他提到的第一件事。没有它意味着他们不得不实施解决方案,这些解决方案将坚持使用.net库,并很快成为遗留代码。
我从来没有使用System.Collections命名空间,并从他的声明这似乎是正确的路径。
0
关于唯一不好的就是我能想到使用泛型的时候是方差,因此,例如,如果你有一个List<Person>
,你想它传递给需要List<object>
你不能因为List<Person>
不能转换的方法直接使用List<object>
。
此问题已在.NET 4.0中解决。
相关问题
- 1. 铸造泛型和泛型类型
- 2. 在System.Collections中找不到ArrayList类型
- 3. JavaFX和泛型
- 4. Java和泛型?
- 5. 泛型和Class.asSubclass
- 6. 泛型和TreeSets
- 7. 厂和泛型
- 8. Java泛型和“...”
- 9. 泛型和ArrayList
- 10. ThreadLocal和泛型
- 11. GWT和泛型
- 12. JRuby和泛型
- 13. IEnumerator和泛型
- 14. DVM和泛型?
- 15. java.lang.Class和泛型
- 16. Scala和泛型
- 17. Hibernate和泛型
- 18. Java泛型类和非泛型类
- 19. System.Collections.Generic vs System.Collections?
- 20. System.Collections VS System.Collections.ObjectModel
- 21. 匿名类型和泛型
- 22. 泛型和类型推断
- 23. Java的泛型和类型
- 24. 反射和泛型类型
- 25. 泛型类型和继承
- 26. 泛型和子类型
- 27. 泛型和可空类型
- 28. F#和泛型类型
- 29. 继承和泛型类型
- 30. 泛型和超类型
KeyedCollection是DictionaryBase的合适替代品,具体取决于您要存储的数据。 –
2009-06-09 21:25:00