Nullable<T> Nullable<T> Nullable<T> Nullable<T> Struct

定義

表示可以指派 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)

類型參數

T

Nullable<T> 泛型型別的基礎實值型別。The underlying value type of the Nullable<T> generic type.

繼承
Nullable<T>Nullable<T>Nullable<T>Nullable<T>
屬性

範例

下列程式碼範例會定義 Microsoft Pubs 範例資料庫中的三個數據表資料列。The following code example defines three rows of a table in the Microsoft Pubs sample database. 資料表包含兩個不可為 null 的資料行,以及兩個可為 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.

備註

如果可以指派一個值或可以指派null一個型別,表示型別沒有任何值,就會被視為可為 null。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. 根據預設,所有的參考型別( String例如)皆可為 null,但所有實值Int32型別(例如)都不是。By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not.

在C#和 Visual Basic 中,您可以使用實值型別後面的?標記法,將實值型別標示為可為 null。In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. 例如, int?在C#或Integer?中 Visual Basic 會宣告可指派null的整數數值型別。For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.

Nullable<T>結構僅支援將實值型別當做可為 null 的型別使用,因為在設計中,參考型別可為 null。The Nullable<T> structure supports using only a value type as a nullable type because reference types are nullable by design.

類別提供Nullable<T>結構的互補支援。 NullableThe Nullable class provides complementary support for the Nullable<T> structure. Nullable類別支援取得可為 null 之型別的基礎型別,以及對其基礎實值型別不支援一般比較和相等運算的可為 null 類型的比較和相等運算。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.

基本屬性Fundamental Properties

Nullable<T>結構的兩個基本成員HasValue為和Value屬性。The two fundamental members of the Nullable<T> structure are the HasValue and Value properties. 如果Nullable<T>物件HasValue的屬性是true,則可以使用Value屬性來存取物件的值。If the HasValue property for a Nullable<T> object is true, the value of the object can be accessed with the Value property. 如果屬性為false,則物件的值為未定義,而嘗試InvalidOperationException存取Value屬性則會擲回。 HasValueIf the HasValue property is false, the value of the object is undefined and an attempt to access the Value property throws an InvalidOperationException.

Boxing 和 UnboxingBoxing and Unboxing

當可為 null 的型別已裝箱時,common language runtime 會自動將Nullable<T>物件的基礎值( Nullable<T>而不是物件本身)方塊。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. 也就是說,如果HasValue屬性為true Value ,則會將屬性的內容裝箱。That is, if the HasValue property is true, the contents of the Value property is boxed. 當可為 null 之型別的基礎值為取消裝箱時,common language runtime 會Nullable<T>建立一個已初始化為基礎值的新結構。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.

如果可HasValue為 null 之類型的屬性false為,則裝箱運算的結果會null是。If the HasValue property of a nullable type is false, the result of a boxing operation is null. 因此,如果將可為 null 的型別傳遞至預期物件引數的方法,則該方法必須準備好處理引數為null的情況。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. null取消加入至可為 null 的型別時,common language runtime Nullable<T>會建立新的HasValue結構, false並將其屬性初始化為。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.1和 Windows 執行階段元件and Windows Runtime Components

從開始Nullable<T> ,您可以將類型包含為 WinMD 程式庫中所匯出結構的成員。 .NET Framework 4.5.1.NET Framework 4.5.1Starting 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. 先前不支援這種情況。Previously, this was not supported.

建構函式

Nullable<T>(T) Nullable<T>(T) Nullable<T>(T) Nullable<T>(T)

Nullable<T> 結構的新執行個體初始化為指定值。Initializes a new instance of the Nullable<T> structure to the specified value.

屬性

HasValue HasValue HasValue HasValue

取得值,指出目前的 Nullable<T> 物件是否具有其基礎類型的有效值。Gets a value indicating whether the current Nullable<T> object has a valid value of its underlying type.

Value Value Value Value

取得目前 Nullable<T> 物件的值,如果這個物件已有指派的有效基礎值。Gets the value of the current Nullable<T> object if it has been assigned a valid underlying value.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

指示目前的 Nullable<T> 物件是否等於指定的物件。Indicates whether the current Nullable<T> object is equal to a specified object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

擷取 Value 屬性所傳回之物件的雜湊碼。Retrieves the hash code of the object returned by the Value property.

GetValueOrDefault() GetValueOrDefault() GetValueOrDefault() GetValueOrDefault()

擷取目前 Nullable<T> 物件的值,或底層型別的預設值。Retrieves the value of the current Nullable<T> object, or the default value of the underlying type.

GetValueOrDefault(T) GetValueOrDefault(T) GetValueOrDefault(T) GetValueOrDefault(T)

擷取目前 Nullable<T> 物件的值,或指定的預設值。Retrieves the value of the current Nullable<T> object, or the specified default value.

ToString() ToString() ToString() ToString()

傳回目前 Nullable<T> 物件值的文字表示。Returns the text representation of the value of the current Nullable<T> object.

運算子

Explicit(Nullable<T> to T) Explicit(Nullable<T> to T) Explicit(Nullable<T> to T) Explicit(Nullable<T> to T)

定義 Nullable<T> 執行個體到其基礎值的明確轉換。Defines an explicit conversion of a Nullable<T> instance to its underlying value.

Implicit(T to Nullable<T>) Implicit(T to Nullable<T>) Implicit(T to Nullable<T>) Implicit(T to Nullable<T>)

建立新 Nullable<T> 已經初始化為指定值的物件。Creates a new Nullable<T> object initialized to a specified value.

適用於

另請參閱