CA1038:枚举数应强类型化
类型名 |
EnumeratorsShouldBeStronglyTyped |
CheckId |
CA1038 |
类别 |
Microsoft.Design |
是否重大更改 |
是 |
原因
某公共类型或受保护类型实现 System.Collections.IEnumerator,但未提供 IEnumerator.Current 属性的强类型版本。 该规则中免除了从以下类型派生的类型:
规则说明
此规则要求 IEnumerator 实现还提供 Current 属性的强类型版本,以使用户在使用该接口提供的功能时不必将返回值强制转换为强类型。 该规则假定实现 IEnumerator 的类型包含强于 Object 的类型的实例集合。
如何解决冲突
要修复与该规则的冲突,请显式实现接口属性(将其声明为 IEnumerator.Current)。 添加被声明为 Current 的公共强类型版本的属性,使其返回强类型对象。
何时禁止显示警告
在实现基于对象的枚举数以与基于对象的集合(如二叉树)一起使用时,可以禁止显示此规则发出的警告。 扩展新集合的类型将定义强类型枚举数并公开强类型属性。
示例
下面的示例演示实现强类型 IEnumerator 类型的正确方法。
using System;
using System.Collections;
namespace DesignLibrary
{
// The ExceptionEnumerator class implements a strongly typed enumerator
// for the ExceptionCollection type.
public class ExceptionEnumerator: IEnumerator
{
private IEnumerator myCollectionEnumerator;
private ExceptionEnumerator () {}
public ExceptionEnumerator(ExceptionCollection collection)
{
myCollectionEnumerator = collection.data.GetEnumerator();
}
// Implement the IEnumerator interface member explicitly.
object IEnumerator.Current
{
get
{
return myCollectionEnumerator.Current;
}
}
// Implement the strongly typed member.
public Exception Current
{
get
{
return (Exception) myCollectionEnumerator.Current;
}
}
// Implement the remaining IEnumerator members.
public bool MoveNext ()
{
return myCollectionEnumerator.MoveNext();
}
public void Reset ()
{
myCollectionEnumerator.Reset();
}
}
public class ExceptionCollection : ICollection
{
internal 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.
IEnumerator IEnumerable.GetEnumerator()
{
return new ExceptionEnumerator(this);
}
public ExceptionEnumerator GetEnumerator()
{
return new ExceptionEnumerator(this);
}
}
}
相关规则
请参见
参考
System.Collections.IEnumerator
System.Collections.CollectionBase