[FxCop.設計規則]4. 避免太多的範型參數

4.     避免太多的範型參數

原文引用:

Avoid excessive parameters on generic types

TypeName:

AvoidExcessiveParametersOnGenericTypes

CheckId:

CA1005

Category:

Microsoft.Design

Message Level:

Error

Certainty:

85%

Breaking Change:

Breaking


Cause: An externally visible generic type has more than two type parameters.

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 expose generic lists

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

Generics DesignGuidelines

引發原因:

一個外部可見的範型類型擁有多於2個範型參數。(譯註:何謂“外部可見”?筆者是這樣理解的,如果某範型類只是作爲某個類的內部類來使用,或者侷限在很小的一個範圍內使用,對其他開發者或者用戶不透明,那麼該範型類即爲外部不可見類;反之,則爲外部可見類,需遵循此規則)

規則描述:

範型類擁有的類型參數越多,它就越難以使用,因爲你必須瞭解和記住每一個參數的意義。在單參數的範型類中,參數的意義是很明顯的(例如:List<T>),或某些特定情況下的二參數範型類(例如:Dictionary<TKey,TValue>)。如果類型參數超過2個,對於用戶來說,使用難度就會變得很大,例如:TooManyTypeParameters<T, K, V>

修復問題:

如果要修復這個問題,請修改設計,使範型類的類型參數個數少於2個。

可否忽略:

除非設計必須使用多於兩個類型參數的範型類型,儘量避免違反這條規則。

編寫和設計範型的時候,要儘量讓它容易理解和使用,這樣可以減少學習的時間,並且還可降低因使用新庫帶來的開發上的成本。

發佈了32 篇原創文章 · 獲贊 3 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章