System (Espacio de nombres)


Biblioteca de clases de .NET Framework
Nullable<(Of <(T>)>) (Estructura)

Actualización: noviembre 2007

Representa un objeto cuyo tipo subyacente es un tipo de valor al que también se le puede asignar nullNothingnullptrreferencia null (Nothing en Visual Basic) como tipo de referencia.

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)
Sintaxis

Visual Basic (Declaración)
<SerializableAttribute> _
Public Structure Nullable(Of T As {Structure, New})
Visual Basic (Uso)
Dim instance As Nullable(Of T)
C#
[SerializableAttribute]
public struct Nullable<T>
where T : struct, new()
Visual C++
[SerializableAttribute]
generic<typename T>
where T : value class, gcnew()
public value class Nullable
J#
J# admite el uso de APIs genéricas pero no admite la declaración de nuevas API.
JScript
JScript no admite el uso de métodos ni tipos genéricos.

Parámetros de tipo

T

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

Comentarios

Se dice que un tipo admite valores NULL si se le puede asignar un valor o se le puede asignar nullNothingnullptrreferencia null (Nothing en Visual Basic), lo que significa que el tipo no tiene ningún valor en absoluto. En consecuencia, un tipo que acepta valores NULL puede expresar tanto un valor, como que no existe ningún valor. Por ejemplo, un tipo de referencia como String admite valores NULL, mientras que un tipo de valor como Int32 no los acepta. Un tipo de valor no acepta valores NULL porque tiene la capacidad justa para expresar los valores apropiados para ese tipo; no tiene la capacidad adicional necesaria para expresar un valor NULL.

La estructura Nullable<(Of <(T>)>) admite que sólo se utilice un tipo de valor como tipo que acepta valores NULL porque hace referencia a los tipos que aceptan valores NULL por diseño.

La clase Nullable proporciona compatibilidad complementaria para la estructura Nullable<(Of <(T>)>). La clase Nullable 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 y cuyos tipos subyacentes de valor no admiten las operaciones genéricas de comparación e igualdad.

Escenario

Utilice tipos que acepten valores NULL para representar algo que existe o no existe, dependiendo de las circunstancias. Por ejemplo, un atributo opcional de una etiqueta HTML podría existir en una etiqueta pero no en otra, o una columna que acepta valores NULL en una tabla de base de datos podría existir en una fila de la tabla pero no en otra.

Puede representar el atributo o la columna como un campo de una clase, y puede definir el campo como un tipo de valor. El campo puede contener todos los valores válidos para el atributo o la columna, pero no puede alojar un valor adicional que indique que el atributo o la columna no existe. En ese caso, defina el campo para que sea de un tipo que acepte valores NULL en lugar de un tipo de valor.

Propiedades fundamentales

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

Conversión boxing y conversión unboxing

Cuando a un tipo que acepta valores NULL se le ha aplicado la conversión boxing, Common Language Runtime aplica la conversión boxing automáticamente al valor subyacente del objeto Nullable<(Of <(T>)>), y no al propio objeto Nullable<(Of <(T>)>). Es decir, si la propiedad HasValue es true, se aplica la conversión boxing al contenido de la propiedad Value. Cuando se ha aplicado la conversión unboxing al valor subyacente de un tipo que acepta valores NULL, Common Language Runtime crea una nueva estructura Nullable<(Of <(T>)>) inicializada en el valor subyacente.

Si la propiedad HasValue de un tipo que acepta valores NULL es false, el resultado de una operación de conversión boxing es nullNothingnullptrreferencia null (Nothing en Visual Basic). Por consiguiente, si un tipo que acepta valores NULL al que se le ha aplicado la conversión boxing se pasa a un método que espera un argumento de objeto, ese método debe estar preparado para controlar el hecho de que el argumento sea nullNothingnullptrreferencia null (Nothing en Visual Basic). Cuando se aplica la conversión boxing de nullNothingnullptrreferencia null (Nothing en Visual Basic) en un tipo que acepta valores NULL, Common Language Runtime crea una nueva estructura Nullable<(Of <(T>)>) e inicializa su propiedad HasValue en false.

Ejemplos

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

Visual Basic
' This code example demonstrates the Nullable(Of T) class.
' The code example defines a database table in which two columns 
' are nullable. In the application, an array of rows is created 
' and initialized. The table rows could subsequently be 
' written to a database.

Imports System

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 'titleAuthor

    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 'Main

    ' 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 dspTA
    End Sub 'Display
End Class 'Sample

'
'This code example produces the following results:
'
'*** 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.
'
C#
// This code example demonstrates the Nullable<T> class.
// The code example defines a database table in which two columns 
// are nullable. In the application, an array of rows is created 
// and initialized. The table rows could subsequently be 
// written to a database.

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();       
       }
    }
}

/*
This code example produces the following results:

*** 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.

*/
Seguridad para subprocesos

Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Plataformas

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Información de versión

.NET Framework

Compatible con: 3.5, 3.0, 2.0

.NET Compact Framework

Compatible con: 3.5, 2.0

XNA Framework

Compatible con: 2.0, 1.0
Vea también

Referencia

Etiquetas :


Page view tracker