CA1007:建議在適當時使用泛型
型別名稱 |
UseGenericsWhereAppropriate |
CheckId |
CA1007 |
分類 |
Microsoft.Design |
中斷變更 |
中斷 |
原因
外部可見的方法會包含 System.Object 型別的參考參數,而且包含的組件 (Assembly) 會以 .NET Framework 2.0 為目標。
規則描述
參考參數是使用 ref (Visual Basic 中的 ByRef) 關鍵字所修改的參數。 提供給參考參數的引數型別 (Argument Type) 必須與參考參數型別完全相符。 若要使用衍生自參考參數型別的型別,則必須先轉型 (Cast) 該型別,並將之指派給參考參數型別的變數。 使用泛型方法可將所有型別 (遵守條件約束) 傳遞給方法,而不需要先將型別轉型為參考參數型別。
如何修正違規
若要修正這個規則的違規情形,請將方法變成泛型,並使用型別參數取代 Object 參數。
隱藏警告的時機
請勿隱藏此規則的警告。
範例
下列範例顯示做為非泛型及泛型方法實作的一般用途交換常式。 請注意,與非泛型方法比較起來,使用泛型方法交換字串更加有效率。
Imports System
Namespace DesignLibrary
Public NotInheritable Class ReferenceParameters
Private Sub New()
End Sub
' This method violates the rule.
Public Shared Sub Swap( _
ByRef object1 As Object, ByRef object2 As Object)
Dim temp As Object = object1
object1 = object2
object2 = temp
End Sub
' This method satifies the rule.
Public Shared Sub GenericSwap(Of T)( _
ByRef reference1 As T, ByRef reference2 As T)
Dim temp As T = reference1
reference1 = reference2
reference2 = temp
End Sub
End Class
Class Test
Shared Sub Main()
Dim string1 As String = "Swap"
Dim string2 As String = "It"
Dim object1 As Object = DirectCast(string1, Object)
Dim object2 As Object = DirectCast(string2, Object)
ReferenceParameters.Swap(object1, object2)
string1 = DirectCast(object1, String)
string2 = DirectCast(object2, String)
Console.WriteLine("{0} {1}", string1, string2)
ReferenceParameters.GenericSwap(string1, string2)
Console.WriteLine("{0} {1}", string1, string2)
End Sub
End Class
End Namespace
using System;
namespace DesignLibrary
{
public sealed class ReferenceParameters
{
private ReferenceParameters(){}
// This method violates the rule.
public static void Swap(ref object object1, ref object object2)
{
object temp = object1;
object1 = object2;
object2 = temp;
}
// This method satifies the rule.
public static void GenericSwap<T>(ref T reference1, ref T reference2)
{
T temp = reference1;
reference1 = reference2;
reference2 = temp;
}
}
class Test
{
static void Main()
{
string string1 = "Swap";
string string2 = "It";
object object1 = (object)string1;
object object2 = (object)string2;
ReferenceParameters.Swap(ref object1, ref object2);
string1 = (string)object1;
string2 = (string)object2;
Console.WriteLine("{0} {1}", string1, string2);
ReferenceParameters.GenericSwap(ref string1, ref string2);
Console.WriteLine("{0} {1}", string1, string2);
}
}
}