Share via


CA1004:泛型方法应提供类型参数

类型名

GenericMethodsShouldProvideTypeParameter

CheckId

CA1004

类别

Microsoft.Design

是否重大更改

原因

外部可见的泛型方法的参数签名不包含与该方法的所有类型参数对应的类型。

规则说明

推理是指由传递给泛型方法的参数的类型来确定该方法的类型参数,而不是显式指定类型参数。 若要启用推理,泛型方法的参数签名必须包含与该方法的类型参数属于相同类型的参数。 在这种情况下,不必指定类型参数。 对所有类型参数都使用推理时,调用泛型实例方法和非泛型实例方法的语法完全相同。 这样可简化泛型方法的使用。

如何解决冲突

若要修复与该规则的冲突,请更改设计以使参数签名包含对于该方法的每个类型参数而言都完全相同的类型。

何时禁止显示警告

不要禁止显示此规则发出的警告。 按照容易理解和使用的语法提供泛型,不仅可以缩短学习新库所需的时间,而且还可以提高新库的使用率。

示例

下面的示例演示了调用两个泛型方法的语法。 InferredTypeArgument 的类型参数是推断出来的,而 NotInferredTypeArgument 的类型参数则必须是显式指定的。

Imports System

Namespace DesignLibrary

   Public Class Inference

      ' This method violates the rule.
      Sub NotInferredTypeArgument(Of T)()

         Console.WriteLine(GetType(T))

      End Sub

      ' This method satisfies the rule.
      Sub InferredTypeArgument(Of T)(sameAsTypeParameter As T)

         Console.WriteLine(sameAsTypeParameter)

      End Sub

   End Class

   Class Test

      Shared Sub Main()

         Dim infer As New Inference()
         infer.NotInferredTypeArgument(Of Integer)()
         infer.InferredTypeArgument(3)

      End Sub

   End Class

End Namespace
using System;

namespace DesignLibrary
{
   public class Inference
   {
      // This method violates the rule.
      public void NotInferredTypeArgument<T>()
      {
         Console.WriteLine(typeof(T));
      }

      // This method satisfies the rule.
      public void InferredTypeArgument<T>(T sameAsTypeParameter)
      {
         Console.WriteLine(sameAsTypeParameter);
      }
   }

   class Test
   {
      static void Main()
      {
         Inference infer = new Inference();
         infer.NotInferredTypeArgument<int>();
         infer.InferredTypeArgument(3);
      }
   }
}

相关规则

CA1005:避免泛型类型的参数过多

CA1010:集合应实现泛型接口

CA1000:不要在泛型类型中声明静态成员

CA1002:不要公开泛型列表

CA1006:不要将泛型类型嵌套在成员签名中

CA1003:使用泛型事件处理程序实例

CA1007:在适用处使用泛型

请参见

参考

泛型(C# 编程指南)