Nullable<T> 구조체

정의

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)

형식 매개 변수

T

Nullable<T> 제네릭 형식의 내부 값 형식입니다.

상속
Nullable<T>
특성

예제

다음 코드 예제에서는 Microsoft Pubs 샘플 데이터베이스에서 테이블의 세 행을 정의합니다. 테이블에는 nullable이 아닌 두 개의 열과 null 허용 열 두 개가 포함되어 있습니다.

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

설명

형식은 값을 할당할 수 있거나 할당 null할 수 있는 경우 null 허용이라고 합니다. 즉, 형식에 값이 전혀 없습니다. 기본적으로 모든 참조 형식(예: Stringnullable)은 null을 허용하지만, 모든 값 형식(예: Int32)은 null을 허용하지 않습니다.

C# 및 Visual Basic 값 형식 뒤의 표기법을 사용하여 값 형식을 ? nullable로 표시합니다. 예를 들어 int? C# 또는 Integer? Visual Basic 할당null할 수 있는 정수 값 형식을 선언합니다.

구조체는 Nullable<T> 참조 형식이 의도적으로 null을 허용하므로 값 형식만 nullable 형식으로 사용할 수 있습니다.

클래스는 Nullable 구조에 대한 Nullable<T> 보완 지원을 제공합니다. 이 클래스는 Nullable nullable 형식의 기본 형식을 가져오고 기본 값 형식이 제네릭 비교 및 같음 연산을 지원하지 않는 nullable 형식 쌍에 대한 비교 및 같음 연산을 지원합니다.

기본 속성

구조체의 Nullable<T> 두 가지 기본 멤버는 및 Value 속성입니다HasValue. 개체의 HasValue 속성 Nullable<T>true면 해당 속성을 사용하여 개체의 값에 Value 액세스할 수 있습니다. 속성이 HasValue false면 개체의 값이 정의되지 않고 속성에 Value 액세스하려고 하면 throw InvalidOperationException됩니다.

boxing 및 unboxing

nullable 형식이 boxed이면 공용 언어 런타임은 개체 자체가 아닌 개체의 Nullable<T> 기본 값을 자동으로 상자로 만듭니 Nullable<T> 다. 즉, 속성이 HasValue 있으면 true속성의 내용이 Value boxed가 됩니다. nullable 형식의 기본 값이 unboxed이면 공용 언어 런타임은 기본 값으로 초기화된 새 Nullable<T> 구조를 만듭니다.

HasValue nullable 형식의 속성이false면 boxing 작업의 결과는 다음과 입니다null. 따라서 boxed nullable 형식이 개체 인수를 예상하는 메서드에 전달되는 경우 해당 메서드는 인수 null가 있는 경우를 처리할 수 있도록 준비해야 합니다. null nullable 형식으로 받은 편지함을 해제하면 공용 언어 런타임에서 새 Nullable<T> 구조를 만들고 해당 HasValue 속성을 false로 초기화합니다.

.NET Framework 4.5.1 및 Windows 런타임 구성 요소

.NET Framework 4.5.1부터 WinMD 라이브러리에서 내보낸 구조체의 멤버로 형식을 포함 Nullable<T> 할 수 있습니다. 이전에는 지원되지 않았습니다.

생성자

Nullable<T>(T)

Nullable<T> 구조체의 새 인스턴스를 지정된 값으로 초기화합니다.

속성

HasValue

현재 Nullable<T> 개체에 해당 내부 형식의 올바른 값이 있는지 여부를 나타내는 값을 가져옵니다.

Value

올바른 내부 형식 값이 할당된 경우 현재 Nullable<T> 개체의 값을 가져옵니다.

메서드

Equals(Object)

현재 Nullable<T> 개체가 지정된 개체와 같은지 여부를 나타냅니다.

GetHashCode()

Value 속성에서 반환하는 개체의 해시 코드를 검색합니다.

GetValueOrDefault()

현재 Nullable<T> 개체의 값 또는 기본 유형의 기본값을 검색합니다.

GetValueOrDefault(T)

현재 Nullable<T> 개체의 값이나 지정된 기본값을 검색합니다.

ToString()

현재 Nullable<T> 개체 값의 텍스트 표현을 반환합니다.

연산자

Explicit(Nullable<T> to T)

Nullable<T> 인스턴스의 명시적 변환을 해당 내부 값으로 정의합니다.

Implicit(T to Nullable<T>)

지정된 값으로 초기화된 새 Nullable<T> 개체를 만듭니다.

적용 대상

추가 정보