ContractArgumentValidatorAttribute 類別

定義

可讓您將舊版 if-then-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 程式代碼來驗證參數,您可能會採用協助程式方法來執行檢查,並在失敗時擲回特定例外狀況,如下列範例所示。

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.RequiresContract.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.EnsuresContract.Requires

建構函式

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)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。

(繼承來源 Attribute)

適用於