ContractArgumentValidatorAttribute 클래스

정의

다시 사용하기 위해 별도의 메서드로 레거시 if-then-throw 코드의 팩터링을 사용하도록 설정하고 throw된 예외 및 인수를 완전히 제어할 수 있도록 합니다.

public ref class ContractArgumentValidatorAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractArgumentValidatorAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false)>]
[<System.Diagnostics.Conditional("CONTRACTS_FULL")>]
type ContractArgumentValidatorAttribute = class
    inherit Attribute
Public NotInheritable Class ContractArgumentValidatorAttribute
Inherits Attribute
상속
ContractArgumentValidatorAttribute
특성

설명

코드에서 명시적 if-then-throw 코드를 사용하여 매개 변수의 유효성을 검사하는 경우 다음 예제와 같이 검사를 수행하고 실패 시 특정 예외를 throw하는 도우미 메서드를 사용할 수 있습니다.

using System;

static class ValidationHelper
{
   public static void NotNull(object argument, string parameterName)
   {
      if (argument == null) throw new ArgumentNullException(parameterName,
                                                            "The parameter cannot be null.");
   }
}

public class Example
{
   public void Execute(string value)
   {
      ValidationHelper.NotNull(value, "value");

      // Body of method goes here.
   }
}
Class ValidationHelper 
   Public Shared Sub NotNull(argument As Object, parameterName As String) 
      If argument Is Nothing Then 
         Throw New ArgumentNullException(parameterName, 
                                         "The parameter cannot be null.")
      End If
   End Sub
End Class

Module Example
   Public Sub Execute(value As String)
      ValidationHelper.NotNull(value, "value")
      
      ' Body of method goes here.
   End Sub
End Module

이 예제 Execute 에서는 매개 변수 값이 되어서는 안 되도록 지정하는 선택적 사전 조건이 있습니다 null. 계약 도구가 에 대한 호출이 계약을 나타내는 것을 인식할 ValidationHelper.NotNull 수 있도록 하려면 호출된 메서드를 특성으로 ContractArgumentValidatorAttribute 표시할 수 있습니다. 메서드 호출은 Contract.EndContractBlock 다음과 같이 도구가 문서 생성 및 정적 검사에 대한 적절한 사양을 추출할 수 있도록 하는 데 사용해야 합니다.

using System;
using System.Diagnostics.Contracts;

static class ValidationHelper
{
   [ContractArgumentValidator]
   public static void NotNull(object argument, string parameterName)
   {
      if (argument == null) throw new ArgumentNullException(parameterName,
                                                            "The parameter cannot be null.");
      Contract.EndContractBlock();
   }
}
Imports System.Diagnostics.Contracts

Class ValidationHelper 
   <ContractArgumentValidator> 
   Public Shared Sub NotNull(argument As Object, parameterName As String) 
      If argument Is Nothing Then 
         Throw New ArgumentNullException(parameterName, 
                                         "The parameter cannot be null.")
         Contract.EndContractBlock()
      End If
   End Sub
End Class

문 외에도 if-then-throw 계약 유효성 검사기 메서드의 계약 섹션에는 다른 계약 유효성 검사기 메서드에 대한 호출이 포함될 수 있습니다. 그러나 다른 계약(예: Contract.Requires또는 Contract.Ensures)은 허용되지 않습니다. 호출 뒤에 Contract.EndContractBlock 나오는 코드는 모든 계약 도구에서 무시됩니다.

다음 예제에서는 기존 NotNull 유효성 검사기 메서드를 기준으로 작성된 범위 인수 유효성 검사기를 보여 줍니다.

using System;
using System.Diagnostics.Contracts;

static class ValidationHelper
{
   [ContractArgumentValidator]
   public static void NotNull(object argument, string parameterName)
   {
      if (argument == null) throw new ArgumentNullException(parameterName,
                                                            "The parameter cannot be null.");
      Contract.EndContractBlock();
   }

   [ContractArgumentValidator]
   public static void InRange(object[] array, int index, string arrayName, string indexName)
   {
      NotNull(array, arrayName);

      if (index < 0)
         throw new ArgumentOutOfRangeException(indexName,
                                               "The index cannot be negative.");
      if (index >= array.Length)
         throw new ArgumentOutOfRangeException(indexName,
                                               "The index is outside the bounds of the array.");
      Contract.EndContractBlock();
   }
}

public class Example
{
   public void Execute(object[] data, int position)
   {
      ValidationHelper.InRange(data, position, "data", "position");

      // Body of method goes here.
   }
}
Imports System.Diagnostics.Contracts

Class ValidationHelper 
   <ContractArgumentValidator> 
   Public Shared Sub NotNull(argument As Object, parameterName As String) 
      If argument Is Nothing Then 
         Throw New ArgumentNullException(parameterName, 
                                         "The parameter cannot be null.")
         Contract.EndContractBlock()
      End If
   End Sub

   <ContractArgumentValidator>
   Public Shared Sub InRange(array() As Object, index As Integer, 
                             arrayName As String, indexName As String)
      NotNull(array, arrayName)
      
      If index < 0 Then 
         Throw New ArgumentOutOfRangeException(indexName, 
                                               "The index cannot be negative.")
      End If                                         
      If index >= array.Length Then 
         Throw New ArgumentOutOfRangeException(indexName, 
                                               "The index is outside the bounds of the array.")
      End If                                                                                              
      Contract.EndContractBlock()
   End Sub
End Class

Module Example
   Public Sub Execute(data() As Object, position As Integer)
      ValidationHelper.InRange(data, position, "data", "position")
      
      ' Body of method goes here.
   End Sub
End Module

사양 관점에서 메서드에는 Execute 다음과 같은 세 가지 계약이 있습니다.

Contract.Requires<ArgumentNullException>(data != null);  
Contract.Requires<ArgumentOutOfRangeException>(position >= 0);  
Contract.Requires<ArgumentOutOfRangeException>(position < data.Length);  

표준 메서드에서 계약 유효성 검사기 메서드에 대한 호출은 또는 Contract.Requires와 같은 Contract.Ensures 다른 계약과 자유롭게 혼합될 수 있습니다.

생성자

ContractArgumentValidatorAttribute()

ContractArgumentValidatorAttribute 클래스의 새 인스턴스를 초기화합니다.

속성

TypeId

파생 클래스에서 구현된 경우 이 Attribute에 대한 고유 식별자를 가져옵니다.

(다음에서 상속됨 Attribute)

메서드

Equals(Object)

이 인스턴스가 지정된 개체와 같은지를 나타내는 값을 반환합니다.

(다음에서 상속됨 Attribute)
GetHashCode()

이 인스턴스의 해시 코드를 반환합니다.

(다음에서 상속됨 Attribute)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
IsDefaultAttribute()

파생 클래스에서 재정의된 경우 이 인스턴스 값이 파생 클래스에 대한 기본값인지 여부를 표시합니다.

(다음에서 상속됨 Attribute)
Match(Object)

파생 클래스에서 재정의된 경우 이 인스턴스가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다.

(다음에서 상속됨 Attribute)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

명시적 인터페이스 구현

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

이름 집합을 해당하는 디스패치 식별자 집합에 매핑합니다.

(다음에서 상속됨 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

인터페이스의 형식 정보를 가져오는 데 사용할 수 있는 개체의 형식 정보를 검색합니다.

(다음에서 상속됨 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

개체에서 제공하는 형식 정보 인터페이스의 수를 검색합니다(0 또는 1).

(다음에서 상속됨 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

개체에서 노출하는 메서드와 속성에 대한 액세스를 제공합니다.

(다음에서 상속됨 Attribute)

적용 대상