CA1006:不要在成員簽章中巢狀化泛型型別
型別名稱 |
DoNotNestGenericTypesInMemberSignatures |
CheckId |
CA1006 |
分類 |
Microsoft.Design |
中斷變更 |
中斷 |
原因
外部可見成員具有內含巢狀型別 (Nested Type) 引數的簽章。
規則描述
巢狀型別引數就是也是泛型型別的型別引數。 若要呼叫其簽章含有巢狀型別引數的成員,則使用者必須具現化 (Instantiate) 一個泛型型別,並將這個型別傳遞給第二個泛型型別的建構函式。 必要程序及語法十分複雜,且應予以避免。
如何修正違規
若要修正此規則的違規情形,請將設計變更成移除巢狀型別引數。
隱藏警告的時機
請勿隱藏此規則的警告。 使用易於了解和使用的語法提供泛型,以便減少學習所需的時間,並增加新程式庫的採用率。
範例
下列範例顯示違反規則的方法,以及呼叫違規方法所需的語法。
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);
}
}
}