Nullable<T> Struct

Definition

表示可分配有 null 的值类型。Represents a value type that can be assigned 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
Public Structure Nullable(Of T)

Type Parameters

T

Nullable<T> 泛型类型的基础值类型。The underlying value type of the Nullable<T> generic type.

Inheritance
Nullable<T>
Attributes

Examples

下面的代码示例定义了 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.

Remarks

如果可以为类型赋值或将其分配到 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. 例如,在 Visual Basic 中C# int?Integer? 声明可以 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 类提供 Nullable<T> 结构的互补支持。The 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> 结构的两个基本成员是 HasValueValue 属性。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. 如果 falseHasValue 属性,则对象的值是不确定的,尝试访问 Value 属性将引发 InvalidOperationExceptionIf the HasValue property is false, the value of the object is undefined and an attempt to access the Value property throws an InvalidOperationException.

装箱和取消装箱Boxing and Unboxing

当对可以为 null 的类型进行装箱时,公共语言运行时将自动框 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 的类型的基础值为取消装箱,则公共语言运行时将创建一个新的 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.

如果 false可以为 null 的类型的 HasValue 属性,则会 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 的类型时,公共语言运行时将创建一个新的 Nullable<T> 结构,并将其 HasValue 属性初始化为 falseWhen 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

.NET Framework 4.5.1.NET Framework 4.5.1开始,可以将 Nullable<T> 类型包含为在 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. 以前,此操作不受支持。Previously, this was not supported.

Constructors

Nullable<T>(T)

Nullable<T> 结构的新实例初始化为指定值。Initializes a new instance of the Nullable<T> structure to the specified value.

Properties

HasValue

获取一个值,该值指示 Nullable<T> 对象是否具有基础类型的有效值。Gets a value indicating whether the current Nullable<T> object has a valid value of its underlying type.

Value

获取当前 Nullable<T> 对象的值,如果它已被分配了有效的基础值。Gets the value of the current Nullable<T> object if it has been assigned a valid underlying value.

Methods

Equals(Object)

指示当前 Nullable<T> 对象是否与指定的对象相等。Indicates whether the current Nullable<T> object is equal to a specified object.

GetHashCode()

检索由 Value 属性返回的对象的哈希代码。Retrieves the hash code of the object returned by the Value property.

GetValueOrDefault()

检索当前 Nullable<T> 对象的值,或基础类型的默认值。Retrieves the value of the current Nullable<T> object, or the default value of the underlying type.

GetValueOrDefault(T)

检索当前 Nullable<T> 对象的值或指定的默认值。Retrieves the value of the current Nullable<T> object, or the specified default value.

ToString()

返回当前 Nullable<T> 对象的值的文本表示形式。Returns the text representation of the value of the current Nullable<T> object.

Operators

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>)

创建一个新的 Nullable<T> 对象,并将其初始化为指定的值。Creates a new Nullable<T> object initialized to a specified value.

Applies to

See also