Nullable<T> Struct

Definizione

Rappresenta un tipo di valore a cui è possibile assegnare null.

generic <typename T>
 where T : value classpublic value class Nullable
public struct Nullable<T> where T : struct
[System.Serializable]
public struct Nullable<T> where T : struct
type Nullable<'T (requires 'T : struct)> = struct
[<System.Serializable>]
type Nullable<'T (requires 'T : struct)> = struct
Public Structure Nullable(Of T)

Parametri di tipo

T

Tipo di valore sottostante del tipo generico Nullable<T> .

Ereditarietà
Nullable<T>
Attributi

Esempio

Nell'esempio di codice seguente vengono definite tre righe di una tabella nel database di esempio Microsoft Pubs. La tabella contiene due colonne che non sono nullable e due colonne che sono nullable.

using System;

class Sample
{
    // Define the "titleAuthor" table of the Microsoft "pubs" database.
    public struct titleAuthor
    {
      // Author ID; format ###-##-####
      public string au_id;
      // Title ID; format AA####
      public string title_id;
      // Author ORD is nullable.
      public short? au_ord;
      // Royalty Percent is nullable.
      public int? royaltyper;
    }

    public static void Main()
    {
      // Declare and initialize the titleAuthor array.
      titleAuthor[] ta = new titleAuthor[3];
      ta[0].au_id = "712-32-1176";
      ta[0].title_id = "PS3333";
      ta[0].au_ord = 1;
      ta[0].royaltyper = 100;

      ta[1].au_id = "213-46-8915";
      ta[1].title_id = "BU1032";
      ta[1].au_ord = null;
      ta[1].royaltyper = null;

      ta[2].au_id = "672-71-3249";
      ta[2].title_id = "TC7777";
      ta[2].au_ord = null;
      ta[2].royaltyper = 40;

      // Display the values of the titleAuthor array elements, and
      // display a legend.
      Display("Title Authors Table", ta);
      Console.WriteLine("Legend:");
      Console.WriteLine("An Author ORD of -1 means no value is defined.");
      Console.WriteLine("A Royalty % of 0 means no value is defined.");
    }

    // Display the values of the titleAuthor array elements.
    public static void Display(string dspTitle,
                               titleAuthor[] dspAllTitleAuthors)
    {
      Console.WriteLine("*** {0} ***", dspTitle);
      foreach (titleAuthor dspTA in dspAllTitleAuthors) {
         Console.WriteLine("Author ID ... {0}", dspTA.au_id);
         Console.WriteLine("Title ID .... {0}", dspTA.title_id);
         Console.WriteLine("Author ORD .. {0}", dspTA.au_ord ?? -1);
         Console.WriteLine("Royalty % ... {0}", dspTA.royaltyper ?? 0);
         Console.WriteLine();
      }
    }
}
// The example displays the following output:
//     *** Title Authors Table ***
//     Author ID ... 712-32-1176
//     Title ID .... PS3333
//     Author ORD .. 1
//     Royalty % ... 100
//
//     Author ID ... 213-46-8915
//     Title ID .... BU1032
//     Author ORD .. -1
//     Royalty % ... 0
//
//     Author ID ... 672-71-3249
//     Title ID .... TC7777
//     Author ORD .. -1
//     Royalty % ... 40
//
//     Legend:
//     An Author ORD of -1 means no value is defined.
//     A Royalty % of 0 means no value is defined.
open System

// Define the "titleAuthor" table of the Microsoft "pubs" database.

type titleAuthor =
  struct
    // Author ID format ###-##-####
    val mutable au_id: string
    // Title ID format AA####
    val mutable title_id: string
    // Author ORD is nullable.
    val mutable au_ord: Nullable<int16>
    // Royalty Percent is nullable.
    val mutable royaltyper: Nullable<int>
  end

// Display the values of the titleAuthor array elements.
let display dspTitle (dspAllTitleAuthors: #seq<titleAuthor>) =
    printfn $"*** {dspTitle} ***"
    for dspTA in dspAllTitleAuthors do
        printfn $"Author ID ... {dspTA.au_id}"
        printfn $"Title ID .... {dspTA.title_id}"
        printfn $"Author ORD .. {dspTA.au_ord.GetValueOrDefault -1s}"
        printfn $"Royalty %% ... {dspTA.royaltyper.GetValueOrDefault -1}\n"

// Declare and initialize the titleAuthor array.
let ta = Array.zeroCreate<titleAuthor> 3
ta[0].au_id <- "712-32-1176"
ta[0].title_id <- "PS3333"
ta[0].au_ord <- Nullable 1s
ta[0].royaltyper <- Nullable 100

ta[1].au_id <- "213-46-8915"
ta[1].title_id <- "BU1032"
ta[1].au_ord <- Nullable()
ta[1].royaltyper <- Nullable()

ta[2].au_id <- "672-71-3249"
ta[2].title_id <- "TC7777"
ta[2].au_ord <- Nullable()
ta[2].royaltyper <- Nullable 40

// Display the values of the titleAuthor array elements, and
// display a legend.
display "Title Authors Table" ta
printfn "Legend:"
printfn "An Author ORD of -1 means no value is defined."
printfn "A Royalty %% of 0 means no value is defined."

// The example displays the following output:
//     *** Title Authors Table ***
//     Author ID ... 712-32-1176
//     Title ID .... PS3333
//     Author ORD .. 1
//     Royalty % ... 100
//
//     Author ID ... 213-46-8915
//     Title ID .... BU1032
//     Author ORD .. -1
//     Royalty % ... 0
//
//     Author ID ... 672-71-3249
//     Title ID .... TC7777
//     Author ORD .. -1
//     Royalty % ... 40
//
//     Legend:
//     An Author ORD of -1 means no value is defined.
//     A Royalty % of 0 means no value is defined.
Class Sample
    ' Define the "titleAuthor" table of the Microsoft "pubs" database. 
    Public Structure titleAuthor
       ' Author ID; format ###-##-####
        Public au_id As String
        ' Title ID; format AA####
        Public title_id As String
        ' Author ORD is nullable.
        Public au_ord As Nullable(Of Short)
        ' Royalty Percent is nullable.
        Public royaltyper As Nullable(Of Integer)
    End Structure 
    
    Public Shared Sub Main() 
       ' Declare and initialize the titleAuthor array.
        Dim ta(2) As titleAuthor
        ta(0).au_id = "712-32-1176"
        ta(0).title_id = "PS3333"
        ta(0).au_ord = 1
        ta(0).royaltyper = 100
        
        ta(1).au_id = "213-46-8915"
        ta(1).title_id = "BU1032"
        ta(1).au_ord = Nothing
        ta(1).royaltyper = Nothing
        
        ta(2).au_id = "672-71-3249"
        ta(2).title_id = "TC7777"
        ta(2).au_ord = Nothing
        ta(2).royaltyper = 40
        
       ' Display the values of the titleAuthor array elements, and 
       ' display a legend.
        Display("Title Authors Table", ta)
        Console.WriteLine("Legend:")
        Console.WriteLine("An Author ORD of -1 means no value is defined.")
        Console.WriteLine("A Royalty % of 0 means no value is defined.")
    End Sub
    
    ' Display the values of the titleAuthor array elements.
    Public Shared Sub Display(ByVal dspTitle As String, _
                              ByVal dspAllTitleAuthors() As titleAuthor) 
        Console.WriteLine("*** {0} ***", dspTitle)
        Dim dspTA As titleAuthor
        For Each dspTA In dspAllTitleAuthors
            Console.WriteLine("Author ID ... {0}", dspTA.au_id)
            Console.WriteLine("Title ID .... {0}", dspTA.title_id)
            Console.WriteLine("Author ORD .. {0}", dspTA.au_ord.GetValueOrDefault(-1))
            Console.WriteLine("Royalty % ... {0}", dspTA.royaltyper.GetValueOrDefault(0))
            Console.WriteLine()
        Next 
    End Sub
End Class 
'This example displays the following output:
'     *** Title Authors Table ***
'     Author ID ... 712-32-1176
'     Title ID .... PS3333
'     Author ORD .. 1
'     Royalty % ... 100
'     
'     Author ID ... 213-46-8915
'     Title ID .... BU1032
'     Author ORD .. -1
'     Royalty % ... 0
'     
'     Author ID ... 672-71-3249
'     Title ID .... TC7777
'     Author ORD .. -1
'     Royalty % ... 40
'     
'     Legend:
'     An Author ORD of -1 means no value is defined.
'     A Royalty % of 0 means no value is defined.

Commenti

La Nullable classe rappresenta un tipo di valore a cui è possibile assegnare null.

Un tipo è detto annullabile se può essere assegnato un valore o può essere assegnato null, il che significa che il tipo non ha alcun valore. Per impostazione predefinita, tutti i tipi di riferimento, ad esempio String, sono annullabili, ma tutti i tipi di valore, ad esempio Int32, non lo sono.

In C# e Visual Basic si contrassegna un tipo di valore come nullable usando la ? notazione dopo il tipo di valore. Ad esempio, int? in C# o Integer? in Visual Basic dichiara un tipo di valore intero a cui è possibile assegnare null.

La Nullable<T> struttura supporta l'uso solo di un tipo di valore come tipo nullable perché i tipi di riferimento sono nullable per progettazione.

La Nullable classe fornisce supporto complementare per la Nullable<T> struttura. La Nullable classe supporta l'acquisizione del tipo sottostante di un tipo nullable e le operazioni di confronto e uguaglianza su coppie di tipi nullable il cui tipo di valore sottostante non supporta operazioni di confronto ed uguaglianza generiche.

Proprietà fondamentali

I due membri fondamentali della Nullable<T> struttura sono le HasValue proprietà e Value . Se la HasValue proprietà per un Nullable<T> oggetto è true, è possibile accedere al valore dell'oggetto con la Value proprietà . Se la HasValue proprietà è false, il valore dell'oggetto non è definito e un tentativo di accesso alla Value proprietà genera un'eccezione InvalidOperationException.

Boxing e unboxing

Quando un tipo nullable viene sottoposto a boxing, il Common Language Runtime effettua automaticamente il boxing del valore sottostante dell'oggetto Nullable<T>, non dell'oggetto Nullable<T> stesso. Ovvero, se la HasValue proprietà è true, i contenuti della Value proprietà vengono sottoposti a boxing. Quando il valore sottostante di un tipo nullable è deconfezionato, il Common Language Runtime crea una nuova Nullable<T> struttura inizializzata al valore sottostante.

Se la HasValue proprietà di un tipo nullable è false, il risultato di un'operazione di boxing è null. Di conseguenza, se un tipo annullabile inscatolato viene passato a un metodo che si aspetta un argomento di tipo oggetto, tale metodo deve essere preparato per gestire il caso in cui l'argomento è null. Quando null è decompresso in un tipo annullabile, Common Language Runtime crea una nuova struttura Nullable<T> e inizializza la sua proprietà HasValue a false.

Componenti di Windows Runtime

È possibile includere un Nullable<T> tipo come membro di una struttura esportata in una libreria WinMD.

Costruttori

Nome Descrizione
Nullable<T>(T)

Inizializza una nuova istanza della Nullable<T> struttura sul valore specificato.

Proprietà

Nome Descrizione
HasValue

Ottiene un valore che indica se l'oggetto corrente Nullable<T> ha un valore valido del tipo sottostante.

Value

Ottiene il valore dell'oggetto corrente Nullable<T> se è stato assegnato un valore sottostante valido.

Metodi

Nome Descrizione
Equals(Object)

Indica se l'oggetto corrente Nullable<T> è uguale a un oggetto specificato.

GetHashCode()

Recupera il codice hash dell'oggetto restituito dalla Value proprietà .

GetValueOrDefault()

Recupera il valore dell'oggetto corrente Nullable<T> o il valore predefinito del tipo sottostante.

GetValueOrDefault(T)

Recupera il valore dell'oggetto corrente Nullable<T> o il valore predefinito specificato.

ToString()

Restituisce la rappresentazione testuale del valore dell'oggetto corrente Nullable<T> .

Operatori

Nome Descrizione
Explicit(Nullable<T> to T)

Definisce una conversione esplicita di un'istanza Nullable<T> nel valore sottostante.

Implicit(T to Nullable<T>)

Crea un nuovo Nullable<T> oggetto inizializzato in un valore specificato.

Si applica a

Vedi anche