更新:2007 年 11 月
| TypeName | ListsAreStronglyTyped | 
| CheckId | CA1039 | 
| 类别 | Microsoft.Design | 
| 是否重大更改 | 是 | 
原因
公共或受保护类型实现了 System.Collections.IList,但是没有为以下的一个或多个项提供强类型方法:
- IList.Item 
- IList.Add 
- IList.Contains 
- IList.IndexOf 
- IList.Insert 
- IList.Remove 
规则说明
该规则要求实现 IList 以提供强类型成员,从而使用户在使用接口提供的功能时不需要将参数强制转换成 System.Object 类型。IList 接口由可以通过索引访问的对象集合实现。该规则假定实现 IList 的类型这样做以管理类型比 Object 更强的实例的集合。
IList 实现 System.Collections.ICollection 和 System.Collections.IEnumerable 接口。如果实现 IList,则必须为 ICollection 提供必需的强类型成员。如果集合中的对象扩展了 System.ValueType,则您必须为 GetEnumerator 提供一个强类型成员,以避免由装箱造成的性能下降;如果集合的对象为引用类型,则不需要提供强类型成员。
为了符合该规则,请使用 InterfaceName.InterfaceMemberName 格式的名称(如 Add)来显式实现接口成员。这些显式接口成员使用由该接口声明的数据类型。使用接口成员名称(如 Add)来实现强类型成员。将强类型成员声明为公共的,将参数和返回值声明为由集合管理的强类型。这些强类型会替换由接口声明的较弱类型,例如 Object 和 Array。
如何修复冲突
要修复与该规则的冲突,请显式实现 IList 成员,并为前面提到的成员提供强类型替代项。有关正确实现 IList 接口和提供所需的强类型成员的代码,请参见下面的示例。
何时禁止显示警告
当实现新的基于对象的集合(如链接列表,其中扩展新集合的类型决定强类型)时,请禁止显示此规则发出的警告。这些类型应当符合该规则并公开强类型成员。
示例
在下面的示例中,如同所有强类型集合那样,类型 YourType 扩展了 System.Collections.CollectionBase。请注意,CollectionBase 为您提供了 IList 接口的显式实现,因此您只需为 IList 和 ICollection 提供强类型成员即可。
using System;
using System.Collections;
namespace DesignLibrary
{
   public class YourType
   {
      // Implementation for your strong type goes here.
      public YourType() {}
   }
   public class YourTypeCollection : CollectionBase
   {
      // Provide the strongly typed members for IList.
      public YourType this[int index]
      {
         get 
         {
            return (YourType) ((IList)this)[index];
         }
         set 
         {
            ((IList)this)[index] =  value;
         }
      }
      public int Add(YourType value)
      {
         return ((IList)this).Add ((object) value);
      }
      public bool Contains(YourType value) 
      {
         return ((IList)this).Contains((object) value);
      }
      public void Insert(int index, YourType value) 
      {
         ((IList)this).Insert(index, (object) value);
      }
      public void Remove(YourType value) 
      {
         ((IList)this).Remove((object) value);
      }
      public int IndexOf(YourType value) 
      {
         return ((IList)this).IndexOf((object) value);
      }
      // Provide the strongly typed member for ICollection.
      public void CopyTo(YourType[] array, int index)
      {
         ((ICollection)this).CopyTo(array, index);
      }
   }
}
相关规则
请参见
参考
System.Collections.CollectionBase
System.Collections.ICollection