CA1006:不要将泛型类型嵌套在成员签名中
类型名 |
DoNotNestGenericTypesInMemberSignatures |
CheckId |
CA1006 |
类别 |
Microsoft.Design |
是否重大更改 |
是 |
原因
外部可见的成员有包含嵌套类型参数的签名。
规则说明
嵌套类型参数是一个类型参数,也是一个泛型类型。 若要调用签名包含嵌套类型参数的成员,用户必须实例化一个泛型类型,并将此类型传递到另一个泛型类型的构造函数。 所需的过程和语法很复杂,应当避免。
如何解决冲突
若要修复与该规则的冲突,请更改设计,移除嵌套类型参数。
何时禁止显示警告
不要禁止显示此规则发出的警告。 按照容易理解和使用的语法提供泛型,不仅可以缩短学习新库所需的时间,而且还可以提高新库的使用率。
示例
下面的示例演示了一个与该规则冲突的方法和调用该冲突方法所需的语法。
Imports System
Imports System.Collections.Generic
Namespace DesignLibrary
Public Class IntegerCollections
Sub NonNestedCollection(collection As ICollection(Of Integer))
For Each I As Integer In DirectCast( _
collection, IEnumerable(Of Integer))
Console.WriteLine(I)
Next
End Sub
' This method violates the rule.
Sub NestedCollection( _
outerCollection As ICollection(Of ICollection(Of Integer)))
For Each innerCollection As ICollection(Of Integer) In _
DirectCast(outerCollection, _
IEnumerable(Of ICollection(Of Integer)))
For Each I As Integer In _
DirectCast(innerCollection, IEnumerable(Of Integer))
Console.WriteLine(I)
Next
Next
End Sub
End Class
Class Test
Shared Sub Main()
Dim collections As New IntegerCollections()
Dim integerListA As New List(Of Integer)()
integerListA.Add(1)
integerListA.Add(2)
integerListA.Add(3)
collections.NonNestedCollection(integerListA)
Dim integerListB As New List(Of Integer)()
integerListB.Add(4)
integerListB.Add(5)
integerListB.Add(6)
Dim integerListC As New List(Of Integer)()
integerListC.Add(7)
integerListC.Add(8)
integerListC.Add(9)
Dim nestedIntegerLists As New List(Of ICollection(Of Integer))()
nestedIntegerLists.Add(integerListA)
nestedIntegerLists.Add(integerListB)
nestedIntegerLists.Add(integerListC)
collections.NestedCollection(nestedIntegerLists)
End Sub
End Class
End Namespace
using System;
using System.Collections.Generic;
namespace DesignLibrary
{
public class IntegerCollections
{
public void NotNestedCollection(ICollection<int> collection)
{
foreach(int i in collection)
{
Console.WriteLine(i);
}
}
// This method violates the rule.
public void NestedCollection(
ICollection<ICollection<int>> outerCollection)
{
foreach(ICollection<int> innerCollection in outerCollection)
{
foreach(int i in innerCollection)
{
Console.WriteLine(i);
}
}
}
}
class Test
{
static void Main()
{
IntegerCollections collections = new IntegerCollections();
List<int> integerListA = new List<int>();
integerListA.Add(1);
integerListA.Add(2);
integerListA.Add(3);
collections.NotNestedCollection(integerListA);
List<int> integerListB = new List<int>();
integerListB.Add(4);
integerListB.Add(5);
integerListB.Add(6);
List<int> integerListC = new List<int>();
integerListC.Add(7);
integerListC.Add(8);
integerListC.Add(9);
List<ICollection<int>> nestedIntegerLists =
new List<ICollection<int>>();
nestedIntegerLists.Add(integerListA);
nestedIntegerLists.Add(integerListB);
nestedIntegerLists.Add(integerListC);
collections.NestedCollection(nestedIntegerLists);
}
}
}