CA1006: не вкладывайте универсальные типы в сигнатуры членов
TypeName |
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);
}
}
}
Связанные правила
CA1005: не используйте слишком много параметров в универсальных типах
CA1010: коллекции должны реализовывать универсальный интерфейс
CA1000: не объявляйте статические элементы в универсальных типах
CA1002: не следует раскрывать универсальные списки
CA1004: универсальные методы должны предоставлять параметр типа
CA1003: используйте экземпляры обработчика универсальных событий
CA1007: используйте универсальные методы, если это уместно
См. также
Ссылки
Универсальные шаблоны (Руководство по программированию на C#)