CA1035:ICollection 实现含有强类型成员

类型名

ICollectionImplementationsHaveStronglyTypedMembers

CheckId

CA1035

类别

Microsoft.Design

是否重大更改

原因

某公共类型或受保护类型实现 System.Collections.ICollection,但没有提供 ICollection.CopyTo 的强类型方法。 CopyTo 的强类型版本必须接受两个参数,并且不能使用 System.ArraySystem.Object 的数组作为第一个参数。

规则说明

此规则要求 ICollection 实现提供强类型成员,以使用户在使用该接口提供的功能时不必将参数强制转换成 Object 类型。 该规则假定实现 ICollection 的类型执行此操作来管理强于 Object 的类型的实例集合。

ICollection 实现 System.Collections.IEnumerable 接口。 如果集合中的对象扩展了 System.ValueType,则您必须为 GetEnumerator 提供一个强类型成员,以避免由装箱造成的性能下降。 当集合的对象是引用类型时,这是不需要的。

要实现接口成员的强类型版本,请使用 InterfaceName.InterfaceMemberName 形式的名称(如 CopyTo)来显式实现接口成员。 这些显式接口成员使用由该接口声明的数据类型。 使用接口成员名称(如 CopyTo)来实现强类型成员。 将强类型成员声明为公共的,将参数和返回值声明为由集合管理的强类型。 这些强类型会替换由接口声明的较弱类型,例如 ObjectArray

如何解决冲突

要修复与该规则的冲突,请显式实现接口成员(将其声明为 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();
      }
   }
}

相关规则

CA1038:枚举数应强类型化

CA1039:列表已强类型化

请参见

参考

System.Array

System.Collections.IEnumerable

System.Collections.ICollection

System.Object