7. 集合类应该实现泛型接口
原文引用:
Collections should implement generic interface
Rule Description To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types such as the following:
How to Fix Violations To fix a violation of this rule, implement one of the following generic collection interfaces:
When to Exclude Messages It is safe to exclude a message from this rule; however, the collection will have a more limited use. Example Code The following example shows a collection, IntegerCollection, that violates the rule. In GenericIntegerCollection, the collection is modified to satisfy the rule by implementing System.Collections.Generic.IEnumerable<T>. Finally, the collection is used to populate a strongly typed stack. [C#] using System; using System.Collections; using System.Collections.Generic;
namespace DesignLibrary { // This class violates the rule. public class IntegerCollection: CollectionBase { // Methods overrides using Int32. }
// This class satisfies the rule. public class GenericIntegerCollection: CollectionBase, IEnumerable<int> { public int Add(int value) { return InnerList.Add(value); }
// Other method overrides using Int32.
public new IEnumerator<int> GetEnumerator() { foreach (int data in InnerList) { yield return data; } } }
class Test { static void Main () { IntegerCollection intCollection = new IntegerCollection();
// The following line would generate a compiler error. //Stack<int> integerStack = new Stack<int>(intCollection);
GenericIntegerCollection genericIntCollection = new GenericIntegerCollection(); genericIntCollection.Add(2); genericIntCollection.Add(4);
Stack<int> integerStack = new Stack<int>(genericIntCollection); Console.WriteLine(integerStack.Pop()); Console.WriteLine(integerStack.Pop()); } } } Related Rules Avoid excessive parameters on generic types Do not declare static members on generic types Do not nest generic types in member signatures Generic methods should provide type parameter Use generic event handler instances Use generics where appropriate See Also |
引起的原因:
一个使用.NET Framework2.0的程序集有一个输出类型实现了System.Collections.IEnumerable接口,但是没有实现System.Collections.Genceric.IEnumerable<T>接口。如果这个类型实现了System.Collections.IDictionary接口,将不被这个规则所检察。
描述:
为了提升一个集合的可用性,应该实现范型集合接口中的一个。这样,这个集合将能够被用来声明下面的范型类。
- System.Collections.Generic.List<T>
- System.Collections.Generic.Queue<T>
- System.Collections.Generic.Stack<T>
修复:
实现下面的范型集合接口中的一个。
- System.Collections.Generic.IEnumerable<T>
- System.Collections.Generic.ICollection<T>
- System.Collections.Generic.IList<T>
例外:
不符合这条规则是安全的,但是,这样将会使你的集合类有更多的使用限制。
译注:
实现至少一个泛型集合接口使你的类型能够被用来构造下面的范型集合类。
- System.Collections.Generic.List<T>
- System.Collections.Generic.Queue<T>
- System.Collections.Generic.Stack<T>
例如在原文的例子中的GenericIntegerCollection对象就可以被用来构造一个Stack<int>对象,但是如果你不实现这些接口,构造Stack<int>对象将会产生一个编译警告。实现范型集合接口将会使你的使用者拥有更多的灵活性去使用你的集合类。