다음을 통해 공유


보간된 문자열(Visual Basic 참조)

문자열을 생성하는 데 사용됩니다. 보간된 문자열은 보간된 식을 포함하는 템플릿 문자열처럼 보입니다. 보간된 문자열은 포함된 보간된 식을 해당 문자열 표현으로 대체하는 문자열을 반환합니다. 이 기능은 Visual Basic 14 이상 버전에서 사용할 수 있습니다.

보간된 문자열의 인수는 복합 형식 문자열보다 이해하기 쉽습니다. 예를 들어 다음 보간된 문자열에는 보간된 두 식과 {hours:hh}다음 두 개의 보간된 식이 {name} 포함됩니다.

Console.WriteLine($"Name = {name}, hours = {hours:hh}")

해당하는 복합 형식 문자열은 다음과 같습니다.

Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours)

보간된 문자열의 구조는 다음과 같습니다.

$"<text> {<interpolated-expression> [,<field-width>] [:<format-string>] } <text> ..."

위치:

  • field-width 는 필드의 문자 수를 나타내는 부호 있는 정수입니다. 양수이면 필드가 오른쪽에 맞춰집니다. 음수이면 왼쪽 맞춤입니다.

  • format-string 는 서식이 지정되는 개체의 형식에 적합한 형식 문자열입니다. 예를 들어 값의 DateTime 경우 표준 날짜 및 시간 형식 문자열 (예: "D" 또는 "d")일 수 있습니다.

중요합니다

$" 사이에 문자열 시작 부분에 공백을 둘 수 없습니다. 이렇게 하면 컴파일러 오류가 발생합니다.

문자열 리터럴을 사용할 수 있는 모든 위치에서 보간된 문자열을 사용할 수 있습니다. 보간된 문자열이 있는 코드가 실행될 때마다 보간된 문자열이 평가됩니다. 이를 통해 보간된 문자열의 정의와 평가를 구분할 수 있습니다.

문자열에서 중괄호("{", "}")를 포함하려면 두 개의 중괄호 "{{" 또는 "}}"를 사용하세요. 자세한 내용은 암시적 변환을 참조하세요.

보간된 문자열에 따옴표("), 콜론(:), 또는 쉼표(,)처럼 보간된 문자열에서 특별한 의미가 있는 다른 문자가 포함된 경우, 리터럴 문자열에서 발생할 때는 이스케이프 처리되어야 합니다. 또는 보간된 식에 포함된 언어 요소인 경우 괄호로 구분된 식에 포함되어야 합니다. 다음 예제에서는 따옴표를 이스케이프하여 결과 문자열에 포함합니다.

Public Module Example
   Public Sub Main()
      Dim name = "Horace"
      Dim age = 34
      Dim s1 = $"He asked, ""Is your name {name}?"", but didn't wait for a reply."
      Console.WriteLine(s1)
      
      Dim s2 = $"{name} is {age:D3} year{If(age = 1, "", "s")} old."
      Console.WriteLine(s2) 
   End Sub
End Module
' The example displays the following output:
'       He asked, "Is your name Horace?", but didn't wait for a reply.
'       Horace is 034 years old.

암시적 변환

보간된 문자열에서 세 가지 암시적 형식 변환이 있습니다.

  1. 보간된 문자열을 .로 String변환합니다. 다음 예제에서는 보간된 문자열 식이 문자열 표현으로 대체된 문자열을 반환합니다. 다음은 그 예입니다.

    Public Module Example
       Public Sub Main()
          Dim name = "Bartholomew"
          Dim s1 = $"Hello, {name}!"  
          Console.WriteLine(s1)
       End Sub
    End Module
    ' The example displays the following output:
    '      Hello, Bartholomew!
    ' </Snippet1>
    

    문자열 해석의 최종 결과입니다. 이중 중괄호("{{" 및 "}}")의 모든 항목은 단일 중괄호로 변환됩니다.

  2. 보간된 문자열을 IFormattable 변수를 통해 변환하면 단일 IFormattable 인스턴스에서 문화권별 콘텐츠를 사용하여 여러 결과 문자열을 생성할 수 있습니다. 이는 개별 문화권에 대한 올바른 숫자 및 날짜 형식과 같은 항목을 포함하는 데 유용합니다. 메서드를 명시적으로 또는 암시적으로 호출 ToString() 하여 문자열의 서식을 지정할 때까지 모든 이중 중괄호("{{" 및 "}}")는 이중 중괄호로 유지됩니다. 포함된 모든 보간 식은 {0}, {1} 등으로 변환됩니다.

    다음 예제에서는 리플렉션을 사용하여 보간된 문자열에서 만든 변수의 IFormattable 필드 및 속성 값뿐만 아니라 멤버를 표시합니다. 또한 변수를 메서드에 Console.WriteLine(String) 전달합니다IFormattable.

    Imports System.Globalization
    Imports System.Reflection
    
    Public Module Example
       Public Sub Main()
          Dim price = 1000
          Dim s2 As IFormattable = $"The cost of this item is {price:C}."  
          ShowInfo(s2)
          CultureInfo.CurrentCulture = New CultureInfo("en-US")
          Console.WriteLine(s2)
          CultureInfo.CurrentCulture = New CultureInfo("fr-FR")
          Console.WriteLine(s2)      
       End Sub
    
       Private Sub ShowInfo(obj As Object)
          Console.WriteLine($"Displaying member information:{vbCrLf}")
          Dim t = obj.GetType()
          Dim flags = BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.NonPublic
          For Each m In t.GetMembers(flags) 
             Console.Write($"   {m.Name} {m.MemberType}")   
             If m.MemberType = MemberTypes.Property Then
                Dim p = t.GetProperty(m.Name, flags)
                Console.Write($"   Value: {p.GetValue(obj)}")         
             End If
             If m.MemberType = MemberTypes.Field Then
                Dim f = t.GetField(m.Name, flags)
                Console.Write($"   Value: {f.GetValue(obj)}")
             End If
             Console.WriteLine()
          Next
          Console.WriteLine($"-------{vbCrLf}")
       End Sub
    End Module
    ' The example displays the following output:
    Displaying member information:
    
    '       get_Format Method
    '       GetArguments Method
    '       get_ArgumentCount Method
    '       GetArgument Method
    '       ToString Method
    '       System.IFormattable.ToString Method
    '       ToString Method
    '       Equals Method
    '       GetHashCode Method
    '       GetType Method
    '       Finalize Method
    '       MemberwiseClone Method
    '       .ctor Constructor
    '       Format Property   Value: The cost of this item is {0:C}.
    '       ArgumentCount Property   Value: 1
    '       _format Field   Value: The cost of this item is {0:C}.
    '       _arguments Field   Value: System.Object[]
    '       -------
    '
    '       The cost of this item is $1,000.00.
    '       The cost of this item is 1 000,00 €.
    ' </Snippet1>
    
    

    보간된 문자열은 리플렉션을 사용해야만 검사할 수 있습니다. 형식 지정 메서드(예: 문자열 서식 지정 메서드)에 WriteLine(String)전달되면 해당 서식 항목이 확인되고 결과 문자열이 반환됩니다.

  3. 보간된 문자열을 복합 형식 문자열을 FormattableString 나타내는 변수로 변환합니다. 예를 들어 복합 형식 문자열을 검사하고 결과 문자열로 렌더링하는 방법을 검사하면 쿼리를 작성하는 경우 삽입 공격으로부터 보호하는 데 도움이 될 수 있습니다. A FormattableString 에는 다음이 포함됩니다.

    이중 중괄호("{{" 및 "}}")의 모든 항목은 서식을 지정할 때까지 이중 중괄호로 유지됩니다. 포함된 모든 보간 식은 등으로 {0}{1}변환됩니다.

    Imports System.Globalization
    
    Public Module Example
       Public Sub Main()
          Dim name = "Bartholomew"
          Dim s3 As FormattableString = $"Hello, {name}!"  
          Console.WriteLine($"String: '{s3.Format}'")
          Console.WriteLine($"Arguments: {s3.ArgumentCount}")
          Console.WriteLine($"Result string: {s3}")
       End Sub
    End Module
    ' The example displays the following output:
    '       String: 'Hello, {0}!'
    '       Arguments: 1
    '       Result string: Hello, Bartholomew!
    
    

참고하십시오