更新:2007 年 11 月
| TypeName | ICollectionImplementationsHaveStronglyTypedMembers | 
| CheckId | CA1035 | 
| 类别 | Microsoft.Design | 
| 是否重大更改 | 是 | 
原因
某公共类型或受保护类型实现 System.Collections.ICollection,但没有提供 ICollection.CopyTo 的强类型方法。CopyTo 的强类型版本必须接受两个参数,并且不能使用 System.Array 或 System.Object 的数组作为第一个参数。
规则说明
该规则需要 ICollection 实现来提供强类型成员,以便不需要用户在使用接口提供的功能时将参数强制转换为 Object 类型。该规则假定实现 ICollection 的类型执行此操作来管理强于 Object 的类型的实例集合。
ICollection 实现 System.Collections.IEnumerable 接口。如果集合中的对象扩展 System.ValueType,则您必须提供 GetEnumerator 的强类型成员以避免由装箱导致的性能损失;如果该集合的对象是引用类型,则没有此要求。
要实现接口成员的强类型版本,请使用 InterfaceName.InterfaceMemberName 形式的名称(如 CopyTo)来显式实现接口成员。这些显式接口成员使用由该接口声明的数据类型。使用接口成员名称(如 CopyTo)来实现强类型成员。将强类型成员声明为公共的,将参数和返回值声明为由集合管理的强类型。这些强类型会替换由接口声明的较弱类型,例如 Object 和 Array。
如何修复冲突
要修复与该规则的冲突,请显式实现接口成员(将其声明为 CopyTo)。添加被声明为 CopyTo 的公共强类型成员,使该成员采用强类型数组作为它的第一个参数。
何时禁止显示警告
在实现基于新对象的集合(如扩展新集合的类型确定强类型的二叉树)时,可以禁止显示此规则发出的警告。这些类型应当符合该规则并公开强类型成员。
示例
下面的示例演示实现 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();
      }
   }
}
相关规则
请参见
参考
System.Collections.IEnumerable