验证公共方法的参数

更新:2007 年 11 月

TypeName

ValidateArgumentsOfPublicMethods

CheckId

CA1062

类别

Microsoft.Design

是否重大更改

原因

外部可见的方法取消对它的某个引用参数的引用,而没有验证该参数是否为 null(在 Visual Basic 中为 Nothing)。

规则说明

传递给外部可见方法的所有引用参数都应当检查是否为 null。适当的情况下,当参数为 null 时将引发 System.ArgumentNullException

如何修复冲突

若要修复与该规则的冲突,请验证每个引用参数是否为 null。

何时禁止显示警告

不要禁止显示此规则发出的警告。

示例

下面的示例演示一个与该规则冲突的方法和一个满足该规则的方法。

Imports System

Namespace DesignLibrary

    Public Class Test

        ' This method violates the rule.
        Sub DoNotValidate(ByVal input As String)

            If input.Length <> 0 Then
                Console.WriteLine(input)
            End If

        End Sub

        ' This method satisfies the rule.
        Sub Validate(ByVal input As String)

            If input Is Nothing Then
                Throw New ArgumentNullException("input")
            End If

            If input.Length <> 0 Then
                Console.WriteLine(input)
            End If

        End Sub

    End Class

End Namespace
using System;

namespace DesignLibrary
{
    public class Test
    {
        // This method violates the rule.
        public void DoNotValidate(string input)
        {
            if (input.Length != 0)
            {
                Console.WriteLine(input);
            }
        }

        // This method satisfies the rule.
        public void Validate(string input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (input.Length != 0)
            {
                Console.WriteLine(input);
            }
        }
    }
}

在 Visual Studio 2005 中,此规则具有一些局限性。其中一种局限性是

它不会检测要传递给执行验证的其他方法的参数。

Public Function Method(ByVal value As String) As String
    EnsureNotNull(value)

    ' Fires incorrectly    
    Return value.ToString()
End Function

Private Sub EnsureNotNull(ByVal value As String)
    If value Is Nothing Then
        Throw (New ArgumentNullException("value"))
    End If
End Sub
public string Method(string value)
{
    EnsureNotNull(value);

    // Fires incorrectly    
    return value.ToString();
}

private void EnsureNotNull(string value)
{
    if (value == null)
        throw new ArgumentNullException("value");
}

另一局限性是它无法理解短路运算符。

Public Function Method(ByVal value1 As String, ByVal value2 As String) As String
    If value1 Is Nothing OrElse value2 Is Nothing Then
        Throw New ArgumentNullException()
    End If

    ' Fires incorrectly    
    Return value1.ToString() + value2.ToString()

End Function
public string Method(string value1, string value2)
{
    if (value1 == null || value2 == null)
        throw new ArgumentNullException(value1 == null ? "value1" : "value2");

    // Fires incorrectly    
    return value1.ToString() + value2.ToString();
}