ContractArgumentValidatorAttribute Classe

Definizione

Abilita il factoring del codice di if-then-throw legacy in metodi separati per il riutilizzo e fornisce il controllo completo sulle eccezioni e sugli argomenti generati.

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
Ereditarietà
ContractArgumentValidatorAttribute
Attributi

Commenti

Se il codice usa codice esplicito if-then-throw per convalidare i parametri, è possibile usare metodi helper che eseguono controlli e generano eccezioni specifiche in caso di errore, come illustrato nell'esempio seguente.

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

In questo esempio, Execute ha una precondizione elettiva che specifica che il valore del parametro non deve essere null. Per consentire agli strumenti del contratto di riconoscere che la chiamata a ValidationHelper.NotNull rappresenta un contratto, è possibile contrassegnare il metodo chiamato con l'attributo ContractArgumentValidatorAttribute . La Contract.EndContractBlock chiamata al metodo deve essere usata per consentire agli strumenti di estrarre le specifiche appropriate per la generazione di documenti e il controllo statico, come indicato di seguito.

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

Oltre alle if-then-throw istruzioni, la sezione del contratto dei metodi del validator del contratto può contenere chiamate ad altri metodi del validator del contratto. Tuttavia, non sono consentiti altri contratti ( ad esempio Contract.Requires, o Contract.Ensures). Il codice che segue la Contract.EndContractBlock chiamata viene ignorato da tutti gli strumenti del contratto.

Nell'esempio seguente viene illustrato un validator di argomenti di intervallo scritto in termini di un metodo validator esistente 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

Dal punto di vista della specifica, il Execute metodo ha i tre contratti seguenti:

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

Nei metodi standard, le chiamate ai metodi di convalida del contratto possono essere combinate liberamente con altri contratti, Contract.Ensures ad esempio o Contract.Requires.

Costruttori

Nome Descrizione
ContractArgumentValidatorAttribute()

Inizializza una nuova istanza della classe ContractArgumentValidatorAttribute.

Proprietà

Nome Descrizione
TypeId

Se implementato in una classe derivata, ottiene un identificatore univoco per questo Attribute.

(Ereditato da Attribute)

Metodi

Nome Descrizione
Equals(Object)

Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

(Ereditato da Attribute)
GetHashCode()

Restituisce il codice hash per questa istanza.

(Ereditato da Attribute)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
IsDefaultAttribute()

Quando sottoposto a override in una classe derivata, indica se il valore di questa istanza è il valore predefinito per la classe derivata.

(Ereditato da Attribute)
Match(Object)

Quando sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

(Ereditato da Attribute)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

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

Esegue il mapping di un set di nomi a un set corrispondente di identificatori dispatch.

(Ereditato da Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo per un oggetto, che può essere utilizzato per ottenere le informazioni sul tipo per un'interfaccia.

(Ereditato da Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera il numero di interfacce di informazioni sul tipo fornite da un oggetto (0 o 1).

(Ereditato da Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornisce l'accesso alle proprietà e ai metodi esposti da un oggetto .

(Ereditato da Attribute)

Si applica a