4. 避免太多的范型参数
原文引用:
Avoid excessive parameters on generic types
Rule Description The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. It is usually obvious with one type parameter, as in List<T>, and in certain cases with two type parameters, as in Dictionary<TKey, TValue>. If there are more than two type parameters, the difficulty becomes too great for most users, for example, TooManyTypeParameters<T, K, V> in C# or TooManyTypeParameters(Of T, Of K, Of V) in Visual Basic. How to Fix Violations To fix a violation of this rule, change the design to use no more than two type parameters. When to Exclude Messages Do not exclude a message from this rule unless the design absolutely requires more than two type parameters. Providing generics in a syntax that is easy to understand and use reduces the time that is required to learn and increases the adoption rate of new libraries. Related Rules Collections should implement generic interface 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 |
引发原因:
一个外部可见的范型类型拥有多于2个范型参数。(译注:何谓“外部可见”?笔者是这样理解的,如果某范型类只是作为某个类的内部类来使用,或者局限在很小的一个范围内使用,对其他开发者或者用户不透明,那么该范型类即为外部不可见类;反之,则为外部可见类,需遵循此规则)
规则描述:
范型类拥有的类型参数越多,它就越难以使用,因为你必须了解和记住每一个参数的意义。在单参数的范型类中,参数的意义是很明显的(例如:List<T>),或某些特定情况下的二参数范型类(例如:Dictionary<TKey,TValue>)。如果类型参数超过2个,对于用户来说,使用难度就会变得很大,例如:TooManyTypeParameters<T, K, V>。
修复问题:
如果要修复这个问题,请修改设计,使范型类的类型参数个数少于2个。
可否忽略:
除非设计必须使用多于两个类型参数的范型类型,尽量避免违反这条规则。
编写和设计范型的时候,要尽量让它容易理解和使用,这样可以减少学习的时间,并且还可降低因使用新库带来的开发上的成本。