Nullable<T> Estructura

Definición

Representa un tipo de valor al que se puede asignar 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)

Parámetros de tipo

T

Tipo de valor subyacente del Nullable<T> tipo genérico.

Herencia
Nullable<T>
Atributos

Ejemplos

En el ejemplo de código siguiente se definen tres filas de una tabla en la base de datos de ejemplo Microsoft Pubs. La tabla contiene dos columnas que no admiten valores NULL y dos columnas que aceptan valores NULL.

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.

Comentarios

La Nullable clase representa un tipo de valor al que se puede asignar null.

Un tipo se considera anulable si se le puede asignar un valor o se le puede asignar null, lo que significa que el tipo no tiene ningún valor. De forma predeterminada, todos los tipos de referencia, como String, admiten valores NULL, pero todos los tipos de valor, como Int32, no.

En C# y Visual Basic, se marca un tipo de valor como nullable mediante la notación ? después del tipo de valor. Por ejemplo, int? en C# o Integer? en Visual Basic declara un tipo de valor entero al que se puede asignar null.

La Nullable<T> estructura solo admite el uso de un tipo de valor como un tipo que acepta valores nulos porque los tipos de referencia son nulos por diseño.

La Nullable clase proporciona compatibilidad complementaria para la Nullable<T> estructura. La Nullable clase admite la obtención del tipo subyacente de un tipo que acepta valores NULL y las operaciones de comparación e igualdad en pares de tipos que aceptan valores NULL cuyo tipo de valor subyacente no admite operaciones genéricas de comparación e igualdad.

Propiedades fundamentales

Los dos miembros fundamentales de la Nullable<T> estructura son las HasValue propiedades y Value . Si la HasValue propiedad de un Nullable<T> objeto es true, se puede tener acceso al valor del objeto con la Value propiedad . Si la HasValue propiedad es false, el valor del objeto no está definido y un intento de obtener acceso a la propiedad Value produce una InvalidOperationException excepción.

Boxing y unboxing

Cuando se empaqueta un tipo que es anulable, el entorno de ejecución común empaqueta automáticamente el valor subyacente del Nullable<T> objeto, no el objeto en sí Nullable<T>. Es decir, si la propiedad HasValue es true, el contenido de la propiedad Value está boxed. Cuando el valor subyacente de un tipo anulable está desempaquetado, el common language runtime crea una nueva Nullable<T> estructura inicializada con el valor subyacente.

Si la HasValue propiedad de un tipo que acepta valores null es false, el resultado de una operación de boxing es null. Por lo tanto, si se pasa un tipo de valor nulo encapsulado a un método que espera un argumento de objeto, ese método debe estar preparado para manejar el caso en que el argumento sea null. Cuando null está desencapsulado en un tipo que acepta valores NULL, Common Language Runtime crea una nueva estructura Nullable<T> e inicializa su propiedad HasValue a false.

Componentes de Windows Runtime

Puede incluir un tipo Nullable<T> como miembro de una estructura exportada en una biblioteca WinMD.

Constructores

Nombre Description
Nullable<T>(T)

Inicializa una nueva instancia de la Nullable<T> estructura en el valor especificado.

Propiedades

Nombre Description
HasValue

Obtiene un valor que indica si el objeto actual Nullable<T> tiene un valor válido de su tipo subyacente.

Value

Obtiene el valor del objeto actual Nullable<T> si se le ha asignado un valor subyacente válido.

Métodos

Nombre Description
Equals(Object)

Indica si el objeto actual Nullable<T> es igual a un objeto especificado.

GetHashCode()

Recupera el código hash del objeto devuelto por la Value propiedad .

GetValueOrDefault()

Recupera el valor del objeto actual Nullable<T> o el valor predeterminado del tipo subyacente.

GetValueOrDefault(T)

Recupera el valor del objeto actual Nullable<T> o el valor predeterminado especificado.

ToString()

Devuelve la representación de texto del valor del objeto actual Nullable<T> .

Operadores

Nombre Description
Explicit(Nullable<T> to T)

Define una conversión explícita de una Nullable<T> instancia a su valor subyacente.

Implicit(T to Nullable<T>)

Crea un nuevo Nullable<T> objeto inicializado en un valor especificado.

Se aplica a

Consulte también