共用方式為


CA1035:ICollection 實作包含強類型成員

型別名稱

ICollectionImplementationsHaveStronglyTypedMembers

CheckId

CA1035

分類

Microsoft.Design

中斷變更

中斷

原因

公用或保護的型別會實作 ICollection,但不會提供 ICollection.CopyTo 的強型別 (Strongly Typed) 方法。CopyTo 的強型別版本必須接受兩個參數,而且不能以 ArrayObject 的陣列做為它的第一個參數。

規則描述

這項規則要求 ICollection 實作提供強型別成員,讓使用者在使用介面所提供的功能時,不需將引數轉換為 Object 型別。此規則假設實作 ICollection 的型別會以這種方式,管理強於 Object 之型別的執行個體 (Instance) 集合。

ICollection 會實作 IEnumerable 介面。如果集合中的物件會擴充 ValueType,您就必須提供 GetEnumerator 的強型別成員,才能避免因 Boxing 而導致的效能降低。當集合的物件是參考型別時,這是不必要。

若要實作介面成員的強型別版本,請使用 InterfaceName.InterfaceMemberName 表單中的名稱 (如 CopyTo) 明確實作介面成員。明確介面成員會使用介面所宣告的資料型別。使用介面成員名稱實作強型別成員,如 CopyTo。將強型別成員宣告為公用,並將參數和傳回值宣告為集合所管理的強型別。強型別會取代較弱式型別,例如介面所宣告的 ObjectArray

如何修正違規

若要修正此規則的違規情形,請明確實作介面成員 (將介面成員宣告為 CopyTo)。加入公用的強型別成員、宣告為 CopyTo,並且以強型別陣列做為它的第一個參數。

隱藏警告的時機

如果您實作新的物件架構集合 (例如二進位樹狀目錄),且其中擴充新集合的型別會判斷強型別時,請隱藏這項規則的警告。這些型別應該遵守這項規則並公開 (Expose) 強型別成員。

範例

下列範例會實作 ICollection 的正確方式。

using System;
using System.Collections;
namespace DesignLibrary
{

   public class ExceptionCollection : ICollection
   {   
      private ArrayList data;

      ExceptionCollection()
      {
         data = new ArrayList();
      }

      // Provide the explicit interface member for ICollection. 
      void ICollection.CopyTo(Array array, int index)
      {
         data.CopyTo(array, index);
      }

      // Provide the strongly typed member for ICollection. 
      public void CopyTo(Exception[] array, int index)
      {
         ((ICollection)this).CopyTo(array, index);
      }

      // Implement the rest of the ICollection members. 
      public int Count
      {
        get 
        {
           return data.Count;
        }
      }

      public object SyncRoot
      {
         get 
        {
           return this; 
        }
      }

      public bool IsSynchronized
      {
         get 
         {
            return false; 
         }
      }

      // The IEnumerable interface is implemented by ICollection. 
      // Because the type underlying this collection is a reference type, 
      // you do not need a strongly typed version of GetEnumerator. 

      public IEnumerator GetEnumerator()
      {
         return data.GetEnumerator();
      }
   }
}

相關規則

CA1038:列舉程式應該是強類型

CA1039:清單為強類型

請參閱

參考

Array

IEnumerable

ICollection

Object