不要在泛型类型中声明静态成员
更新:2007 年 11 月
TypeName |
DoNotDeclareStaticMembersOnGenericTypes |
CheckId |
CA1000 |
类别 |
Microsoft.Design |
是否重大更改 |
是 |
原因
外部可见的泛型类型包含 static(在 Visual Basic 中为 Shared)成员。
规则说明
调用泛型类型的 static 成员时,必须指定该类型的类型参数。当调用不支持推理的泛型实例成员时,必须指定该成员的类型参数。在上述两种情况下,指定类型参数的语法有所不同且易于混淆,下面的调用说明了这一点:
' Shared method in a generic type.
GenericType(Of Integer).SharedMethod()
' Generic instance method that does not support inference.
someObject.GenericMethod(Of Integer)()
// Static method in a generic type.
GenericType<int>.StaticMethod();
// Generic instance method that does not support inference.
someObject.GenericMethod<int>();
通常,前面的两种声明均应避免,以便在调用成员时不必指定类型参数。这样,调用泛型中的成员所用的语法与调用非泛型中的成员所用的语法别无二致。有关更多信息,请参见 泛型方法应提供类型参数。
如何修复冲突
若要修复与该规则的冲突,请移除静态成员或将它更改为实例成员。
何时禁止显示警告
不要禁止显示此规则发出的警告。按照容易理解和使用的语法提供泛型,不仅可以缩短学习新库所需的时间,而且还可以提高新库的使用率。
示例
下面的示例演示一个导致此冲突的方法。
Imports System
Imports System.Runtime.InteropServices
Namespace Samples
Public NotInheritable Class EnumParser(Of T)
Private Sub New()
End Sub
' Fires this violation
Public Shared Function TryParse(ByVal value As String, <Out()> ByRef result As T) As Boolean
Try
result = DirectCast([Enum].Parse(GetType(T), value), T)
Return True
Catch ex As ArgumentException
End Try
result = Nothing
Return False
End Function
End Class
Module Program
Public Sub Main()
Dim result As DayOfWeek
' Must specify type argument
If EnumParser(Of DayOfWeek).TryParse("Monday", result) Then
Console.WriteLine("Conversion Succeeded!")
End If
End Sub
End Module
End Namespace
using System;
namespace Samples
{
public static class EnumParser<T>
{ // Fires this violation
public static bool TryParse(string value, out T result)
{
try
{
result = (T)Enum.Parse(typeof(T), value);
return true;
}
catch (ArgumentException)
{
}
result = default(T);
return false;
}
}
static class Program
{
public static void Main()
{
DayOfWeek dayOfWeek;
// Must specify type argument
if (EnumParser<DayOfWeek>.TryParse("Monday", out dayOfWeek))
{
Console.WriteLine("Conversion Succeeded!");
}
}
}
}
在上面的示例中,在泛型类型上声明一个静态成员会强制用户在调用该类型时指定类型参数。
下面的示例修复了上面的冲突,所采用的办法是将类型参数 T 从类移动到方法,从而使其可以由编译器在调用时对其进行推断。