Nullable<T> Estructura

Definición

Representa un tipo de valor que se puede asignar como null.Represents a value type that can be assigned null.

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

Parámetros de tipo

T

Tipo de valor subyacente del tipo genérico Nullable<T>.The underlying value type of the Nullable<T> generic type.

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 pubs de Microsoft.The following code example defines three rows of a table in the Microsoft Pubs sample database. La tabla contiene dos columnas que no admiten valores NULL y dos columnas que aceptan valores NULL.The table contains two columns that are not nullable and two columns that are nullable.

using namespace System;

// Define the "titleAuthor" table of the Microsoft "pubs" database.
value struct titleAuthor
{
    public:
       // Author ID; format ###-##-####
       String^ au_id;
       // Title ID; format AA####
       String^ title_id;
       // Author ORD is nullable.
       Nullable<short> au_ord;
       // Royalty Percent is nullable.
       Nullable<int> royaltyper;

    // Display the values of the titleAuthor array elements.
    static void Display(String^ dspTitle,
                        array<titleAuthor>^ dspAllTitleAuthors)
    {
       Console::WriteLine("*** {0} ***", dspTitle);
       for each (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.HasValue ?
                             dspTA.au_ord.Value : -1);
          Console::WriteLine("Royalty % ... {0}", dspTA.royaltyper.HasValue ?
                             dspTA.royaltyper.Value : 0);
          Console::WriteLine();
       }
    }
};

void main()
{
    // Declare and initialize the titleAuthor array.
    array<titleAuthor>^ ta = gcnew array<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 = nullptr;
//    ta[1].royaltyper = nullptr;

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

   // Display the values of the array elements, and
   // display a legend.
    titleAuthor::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.");
}
// 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.
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.
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

Se dice que un tipo admite valores NULL si se le puede asignar un valor o se puede asignar null, lo que significa que el tipo no tiene ningún valor.A type is said to be nullable if it can be assigned a value or can be assigned null, which means the type has no value whatsoever. De forma predeterminada, todos los tipos de referencia String, como, aceptan valores NULL, pero todos los tipos de Int32valor, como, no lo son.By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not.

En C# y Visual Basic, se marca un tipo de valor como que acepta valores NULL ? mediante la notación después del tipo de valor.In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. Por ejemplo, int? en C# o Integer? en Visual Basic declara un tipo de valor entero que se puede asignar null.For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.

La Nullable<T> estructura admite el uso de solo un tipo de valor como un tipo que acepta valores NULL, ya que los tipos de referencia aceptan valores NULL por diseño.The Nullable<T> structure supports using only a value type as a nullable type because reference types are nullable by design.

La Nullable clase proporciona compatibilidad complementaria para la Nullable<T> estructura.The Nullable class provides complementary support for the Nullable<T> structure. 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 de comparación y igualdad genéricas.The Nullable class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations.

Propiedades fundamentalesFundamental Properties

Los dos miembros fundamentales de la Nullable<T> estructura son las HasValue propiedades Value y.The two fundamental members of the Nullable<T> structure are the HasValue and Value properties. Si la HasValue propiedad de un Nullable<T> objeto es true, se puede tener acceso al valor del objeto con la Value propiedad.If the HasValue property for a Nullable<T> object is true, the value of the object can be accessed with the Value property. Si la HasValue propiedad es false, el valor del objeto es indefinido y un intento de obtener acceso a Value la propiedad produce una InvalidOperationExceptionexcepción.If the HasValue property is false, the value of the object is undefined and an attempt to access the Value property throws an InvalidOperationException.

Conversión boxing y conversión unboxingBoxing and Unboxing

Cuando se aplica la conversión boxing a un tipo que acepta valores NULL, el Common Language Runtime de Nullable<T> forma automática el valor Nullable<T> subyacente del objeto, no el propio objeto.When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable<T> object, not the Nullable<T> object itself. Es decir, si la HasValue propiedad es true, se aplica la conversión Value Boxing al contenido de la propiedad.That is, if the HasValue property is true, the contents of the Value property is boxed. Cuando se aplica la conversión unboxing al valor subyacente de un tipo que acepta valores NULL, Nullable<T> el Common Language Runtime crea una nueva estructura inicializada en el valor subyacente.When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable<T> structure initialized to the underlying value.

Si la HasValue propiedad de un tipo que acepta valores falseNULL es, el resultado de una operación nullde conversión boxing es.If the HasValue property of a nullable type is false, the result of a boxing operation is null. Por consiguiente, si se pasa un tipo que acepta valores NULL con conversión boxing a un método que espera un argumento de objeto, ese método debe estar preparado para controlar el caso nullen el que el argumento es.Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is null. Cuando null se aplica la conversión unboxing en un tipo que acepta valores NULL, Nullable<T> el Common Language Runtime crea una nueva HasValue estructura e falseinicializa su propiedad en.When null is unboxed into a nullable type, the common language runtime creates a new Nullable<T> structure and initializes its HasValue property to false.

.NET Framework 4.5.1.NET Framework 4.5.1y Windows Runtime componentesand Windows Runtime Components

A partir Nullable<T> de .NET Framework 4.5.1.NET Framework 4.5.1, puede incluir un tipo como miembro de una estructura exportada en una biblioteca WinMD.Starting with the .NET Framework 4.5.1.NET Framework 4.5.1, you can include a Nullable<T> type as a member of a structure exported in a WinMD library. Anteriormente, esto no era compatible.Previously, this was not supported.

Constructores

Nullable<T>(T)

Inicializa una nueva instancia de la estructura Nullable<T> en el valor especificado.Initializes a new instance of the Nullable<T> structure to the specified value.

Propiedades

HasValue

Obtiene un valor que indica si el objeto Nullable<T> actual tiene un valor válido de su tipo subyacente.Gets a value indicating whether the current Nullable<T> object has a valid value of its underlying type.

Value

Obtiene el valor del objeto Nullable<T> actual si se ha asignado un valor subyacente válido.Gets the value of the current Nullable<T> object if it has been assigned a valid underlying value.

Métodos

Equals(Object)

Indica si el objeto Nullable<T> actual es igual a un objeto especificado.Indicates whether the current Nullable<T> object is equal to a specified object.

GetHashCode()

Recupera el código hash del objeto devuelto por la propiedad Value.Retrieves the hash code of the object returned by the Value property.

GetValueOrDefault()

Recupera el valor del objeto Nullable<T> actual o el valor predeterminado del tipo subyacente.Retrieves the value of the current Nullable<T> object, or the default value of the underlying type.

GetValueOrDefault(T)

Recupera el valor del objeto Nullable<T> actual o el valor predeterminado especificado.Retrieves the value of the current Nullable<T> object, or the specified default value.

ToString()

Devuelve la representación de texto del valor del objeto Nullable<T> actual.Returns the text representation of the value of the current Nullable<T> object.

Operadores

Explicit(Nullable<T> to T)

Define una conversión explícita de una instancia Nullable<T> a su valor subyacente.Defines an explicit conversion of a Nullable<T> instance to its underlying value.

Implicit(T to Nullable<T>)

Crea un nuevo objeto Nullable<T> inicializado en un valor especificado.Creates a new Nullable<T> object initialized to a specified value.

Se aplica a

Consulte también: