更新 : 2007 年 11 月
TypeName |
ValidateArgumentsOfPublicMethods |
CheckId |
CA1062 |
カテゴリ |
Microsoft.Design |
互換性に影響する変更点 |
なし |
原因
引数が null (Visual Basic では Nothing) であるかどうかを確認せずに、外部から参照可能なメソッドが参照引数の 1 つを逆参照しています。
規則の説明
外部から参照可能なメソッドに渡されるすべての参照引数について、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 では、この規則にいくつかの制限事項があります。その 1 つは、
検証を行う別のメソッドに渡されるパラメータが検出されないということです。
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");
}
もう 1 つの制限事項は、ショートサーキット演算子が認識されないということです。
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();
}