共用方式為


驗證公用方法的引數

更新:2007 年 11 月

型別名稱

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();
}