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 샘플 데이터베이스에서 테이블의 세 행을 정의합니다. 테이블에는 null을 허용하지 않는 열 2개와 null 허용 열 2개가 포함되어 있습니다.

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.

설명

클래스는 Nullable 할당 null할 수 있는 값 형식을 나타냅니다.

형식은 값을 할당하거나 null로 할당할 수 있는 경우 null을 허용한다고 합니다. 즉, null이란 형식에 값이 전혀 없음을 의미합니다. 기본적으로 String과 같은 모든 참조 형식은 null을 허용하지만, Int32과 같은 모든 값 형식은 허용하지 않습니다.

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

구조체 Nullable<T>는 참조 형식이 본래 null을 허용하기 때문에 값 형식만 nullable 형식으로 사용할 수 있도록 지원합니다.

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

기본 속성

구조체의 두 가지 기본 멤버는 Nullable<T>HasValue 속성 및 Value입니다. HasValue 개체에 대한 Nullable<T> 속성이 true인 경우, Value 속성을 통해 개체 값을 액세스할 수 있습니다. 속성 HasValuefalse인 경우 개체의 값은 정의되지 않으며, Value 속성에 액세스하려고 하면 InvalidOperationException가 발생합니다.

박싱 및 언박싱

nullable 형식이 박싱될 때, 공용 언어 런타임은 Nullable<T> 개체 자체가 아닌 Nullable<T> 개체의 기본 값을 자동으로 박싱합니다. 즉, HasValue 속성이 true이면 Value 속성의 내용이 "박스화"됩니다. nullable 형식의 기본 값이 언박싱되면, 공용 언어 런타임은 기본 값으로 초기화된 새로운 Nullable<T> 구조체를 생성합니다.

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

Windows 런타임 구성 요소

WinMD 라이브러리에서 내보낸 구조체의 멤버로 Nullable<T> 타입을 포함할 수 있습니다.

생성자

Name Description
Nullable<T>(T)

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

속성

Name Description
HasValue

현재 Nullable<T> 개체에 기본 형식의 유효한 값이 있는지 여부를 나타내는 값을 가져옵니다.

Value

유효한 기본 값이 할당된 경우 현재 Nullable<T> 개체의 값을 가져옵니다.

메서드

Name Description
Equals(Object)

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

GetHashCode()

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

GetValueOrDefault()

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

GetValueOrDefault(T)

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

ToString()

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

연산자

Name Description
Explicit(Nullable<T> to T)

인스턴스를 기본 값으로 Nullable<T> 명시적으로 변환하는 방법을 정의합니다.

Implicit(T to Nullable<T>)

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

적용 대상

추가 정보