Object.ToString 메서드

정의

현재 개체를 나타내는 문자열을 반환합니다.

public:
 virtual System::String ^ ToString();
public virtual string ToString ();
public virtual string? ToString ();
abstract member ToString : unit -> string
override this.ToString : unit -> string
Public Overridable Function ToString () As String

반환

현재 개체를 나타내는 문자열입니다.

설명

Object.ToString는 .NET Framework 주요 서식 지정 메서드입니다. 표시에 적합하도록 개체를 문자열 표현으로 변환합니다. (.NET Framework 서식 지원에 대한 자세한 내용은 형식 서식 지정을 참조하세요. 메서드의 Object.ToString 기본 구현은 개체 형식의 정규화된 이름을 반환합니다.

중요

다른 형식의 멤버 목록에서 링크를 따라 이 페이지에 도달했을 수 있습니다. 해당 형식이 를 재정 Object.ToString의하지 않기 때문입니다. 대신 메서드의 Object.ToString 기능을 상속합니다.

형식은 특정 형식의 Object.ToString 보다 적합한 문자열 표현을 제공하기 위해 메서드를 재정의하는 경우가 자주 있습니다. 형식은 형식 문자열 또는 문화권 구분 서식 지정을 지원하기 위해 메서드를 오버로드 Object.ToString 하는 경우가 자주 있습니다.

이 섹션의 내용은 다음과 같습니다.

기본 Object.ToString() 메서드
Object.ToString() 메서드 재정의
ToString 메서드 오버로드
Object.ToString 메서드 확장
Windows 런타임 대한 참고 사항

기본 Object.ToString() 메서드

메서드의 ToString 기본 구현은 다음 예제와 같이 형식 Object의 정규화된 이름을 반환합니다.

using namespace System;

void main()
{
   Object^ obj = gcnew Object();
   Console::WriteLine(obj->ToString());
}
// The example displays the following output:
//      System.Object
Object obj = new Object();
Console.WriteLine(obj.ToString());

// The example displays the following output:
//      System.Object
let obj = obj ()
printfn $"{obj.ToString()}"
// printfn $"{obj}" // Equivalent

// The example displays the following output:
//      System.Object
Module Example
   Public Sub Main()
      Dim obj As New Object()
      Console.WriteLine(obj.ToString())
   End Sub
End Module
' The example displays the following output:
'      System.Object

Object 는 .NET Framework 모든 참조 형식의 기본 클래스이므로 이 동작은 메서드를 재정 ToString 의하지 않는 참조 형식에 의해 상속됩니다. 다음은 이에 대한 예입니다. 모든 Object 멤버의 기본 구현을 허용하는 라는 Object1 클래스를 정의합니다. 해당 ToString 메서드는 개체의 정규화된 형식 이름을 반환합니다.

using namespace System;

namespace Examples
{
   ref class Object1
   {
   };
}

void main()
{
   Object^ obj1 = gcnew Examples::Object1();
   Console::WriteLine(obj1->ToString());
}
// The example displays the following output:
//   Examples.Object1
using System;
using Examples;

namespace Examples
{
   public class Object1
   {
   }
}

public class Example
{
   public static void Main()
   {
      object obj1 = new Object1();
      Console.WriteLine(obj1.ToString());
   }
}
// The example displays the following output:
//   Examples.Object1
type Object1() = class end

let obj1 = Object1()
printfn $"{obj1.ToString()}"
// The example displays the following output:
//   Examples.Object1
Imports Examples

Namespace Examples
   Public Class Object1
   End Class
End Namespace

Module Example
   Public Sub Main()
      Dim obj1 As New Object1()
      Console.WriteLine(obj1.ToString())
   End Sub
End Module
' The example displays the following output:
'   Examples.Object1

Object.ToString() 메서드 재정의

형식은 일반적으로 메서드를 재정의 Object.ToString 하여 instance 개체를 나타내는 문자열을 반환합니다. 예를 들어 , 및 와 같은 Char기본 형식은 개체가 나타내는 값의 문자열 형식을 반환하는 구현을 제공합니다ToString.StringInt32 다음 예제에서는 클래스를 정의 합니다 Object2재정의 ToString 하는 클래스는 해당 값과 함께 형식 이름을 반환 하는 메서드입니다.

using namespace System;

ref class Object2
{
   private:
      Object^ value;

   public:
      Object2(Object^ value)
      {
         this->value = value;
      }

      virtual String^ ToString() override
      {
         return Object::ToString() + ": " + value->ToString();
      }
};

void main()
{
   Object2^ obj2 = gcnew Object2(L'a');
   Console::WriteLine(obj2->ToString());
 
}
// The example displays the following output:
//       Object2: a
using System;

public class Object2
{
   private object value;

   public Object2(object value)
   {
      this.value = value;
   }

   public override string ToString()
   {
      return base.ToString() + ": " + value.ToString();
   }
}

public class Example
{
   public static void Main()
   {
      Object2 obj2 = new Object2('a');
      Console.WriteLine(obj2.ToString());
   }
}
// The example displays the following output:
//       Object2: a
type Object2(value: obj) =
    inherit obj ()
    override _.ToString() =
        base.ToString() + ": " + value.ToString()

let obj2 = Object2 'a'
printfn $"{obj2.ToString()}"
// The example displays the following output:
//       Object2: a
Public Class Object2
   Private value As Object
   
   Public Sub New(value As Object)
      Me.value = value
   End Sub
   
   Public Overrides Function ToString() As String
      Return MyBase.ToString + ": " + value.ToString()
   End Function
End Class

Module Example
   Public Sub Main()
      Dim obj2 As New Object2("a"c)
      Console.WriteLine(obj2.ToString())
   End Sub
End Module
' The example displays the following output:
'       Object2: a

다음 표에서는 .NET의 형식 범주를 나열하고 메서드를 재정의 Object.ToString 하는지 여부를 나타냅니다.

형식 범주 Object.ToString()을 재정의합니다. 동작
클래스 해당 없음 해당 없음
구조체 예(ValueType.ToString) Object.ToString()과 동일
열거형 예(Enum.ToString()) 멤버 이름
인터페이스 해당 없음
대리자 해당 없음

재정의에 대한 자세한 내용은 상속자에 대한 참고 사항 섹션을 참조하세요 ToString.

ToString 메서드 오버로드

매개 변수 없는 Object.ToString() 메서드를 재정의하는 것 외에도 많은 형식이 ToString 메서드를 오버로드하여 매개 변수를 허용하는 메서드의 버전을 제공합니다. 가장 일반적으로 이 작업은 변수 서식 지정 및 문화권 구분 서식에 대한 지원을 제공하기 위해 수행됩니다.

다음 예에서는 클래스의 ToString 다양한 필드 값을 포함하는 결과 문자열을 반환하기 위해 메서드를 오버로드합니다 Automobile . 모델 이름과 연도를 반환하는 네 가지 형식 문자열인 G를 정의합니다. D- 모델 이름, 연도 및 문 수를 반환합니다. C는 모델 이름, 연도 및 실린더 수를 반환합니다. 및 4개의 필드 값이 모두 있는 문자열을 반환하는 A입니다.

using System;

public class Automobile
{
   private int _doors;
   private string _cylinders;
   private int _year;
   private string _model;

   public Automobile(string model, int year , int doors,
                     string cylinders)
   {
      _model = model;
      _year = year;
      _doors = doors;
      _cylinders = cylinders;
   }

   public int Doors
   { get { return _doors; } }

   public string Model
   { get { return _model; } }

   public int Year
   { get { return _year; } }

   public string Cylinders
   { get { return _cylinders; } }

   public override string ToString()
   {
      return ToString("G");
   }

   public string ToString(string fmt)
   {
      if (string.IsNullOrEmpty(fmt))
         fmt = "G";

      switch (fmt.ToUpperInvariant())
      {
         case "G":
            return string.Format("{0} {1}", _year, _model);
         case "D":
            return string.Format("{0} {1}, {2} dr.",
                                 _year, _model, _doors);
         case "C":
            return string.Format("{0} {1}, {2}",
                                 _year, _model, _cylinders);
         case "A":
            return string.Format("{0} {1}, {2} dr. {3}",
                                 _year, _model, _doors, _cylinders);
         default:
            string msg = string.Format("'{0}' is an invalid format string",
                                       fmt);
            throw new ArgumentException(msg);
      }
   }
}

public class Example
{
   public static void Main()
   {
      var auto = new Automobile("Lynx", 2016, 4, "V8");
      Console.WriteLine(auto.ToString());
      Console.WriteLine(auto.ToString("A"));
   }
}
// The example displays the following output:
//       2016 Lynx
//       2016 Lynx, 4 dr. V8
open System

type Automobile(model: string, year: int, doors: int, cylinders: string) =
    member _.Doors = doors
    member _.Model = model
    member _.Year = year
    member _.Cylinders = cylinders

    override this.ToString() =
        this.ToString "G"

    member _.ToString(fmt) =
        let fmt = 
            if String.IsNullOrEmpty fmt then "G"
            else fmt.ToUpperInvariant()

        match fmt with
        | "G" ->
            $"{year} {model}"
        | "D" ->
            $"{year} {model}, {doors} dr."
        | "C" ->
            $"{year} {model}, {cylinders}"
        | "A" ->
            $"{year} {model}, {doors} dr. {cylinders}"
        | _ ->
            raise (ArgumentException $"'{fmt}' is an invalid format string")

let auto = Automobile("Lynx", 2016, 4, "V8")
printfn $"{auto}"
printfn $"""{auto.ToString "A"}"""
// The example displays the following output:
//       2016 Lynx
//       2016 Lynx, 4 dr. V8
Public Class Automobile
   Private _doors As Integer
   Private _cylinders As String
   Private _year As Integer
   Private _model As String
   
   Public Sub New(model As String, year As Integer, doors As Integer,
                  cylinders As String)
      _model = model
      _year = year
      _doors = doors
      _cylinders = cylinders
   End Sub
   
   Public ReadOnly Property Doors As Integer
      Get
          Return _doors
      End Get
   End Property
   
   Public ReadOnly Property Model As String
      Get
         Return _model
      End Get
   End Property
   
   Public ReadOnly Property Year As Integer
      Get
         Return _year
      End Get
   End Property
   
   Public ReadOnly Property Cylinders As String
      Get
         Return _cylinders
      End Get
   End Property
   
   Public Overrides Function ToString() As String
      Return ToString("G")
   End Function
   
   Public Overloads Function ToString(fmt As String) As String
      If String.IsNullOrEmpty(fmt) Then fmt = "G"
      
      Select Case fmt.ToUpperInvariant()
         Case "G"
            Return String.Format("{0} {1}", _year, _model)
         Case "D"
            Return String.Format("{0} {1}, {2} dr.",
                                 _year, _model, _doors)
         Case "C"
            Return String.Format("{0} {1}, {2}",
                                 _year, _model, _cylinders)
         Case "A"
            Return String.Format("{0} {1}, {2} dr. {3}",
                                 _year, _model, _doors, _cylinders)
         Case Else
            Dim msg As String = String.Format("'{0}' is an invalid format string",
                                              fmt)
            Throw New ArgumentException(msg)
      End Select
   End Function
End Class

Module Example
   Public Sub Main()
      Dim auto As New Automobile("Lynx", 2016, 4, "V8")
      Console.WriteLine(auto.ToString())
      Console.WriteLine(auto.ToString("A"))
   End Sub
End Module
' The example displays the following output:
'       2016 Lynx
'       2016 Lynx, 4 dr. V8

다음 예제에서는 오버로드된 Decimal.ToString(String, IFormatProvider) 메서드를 호출하여 통화 값의 문화권 구분 서식을 표시합니다.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "en-GB", "fr-FR",
                                "hr-HR", "ja-JP" };
      Decimal value = 1603.49m;
      foreach (var cultureName in cultureNames) {
         CultureInfo culture = new CultureInfo(cultureName);
         Console.WriteLine("{0}: {1}", culture.Name,
                           value.ToString("C2", culture));
      }
   }
}
// The example displays the following output:
//       en-US: $1,603.49
//       en-GB: £1,603.49
//       fr-FR: 1 603,49 €
//       hr-HR: 1.603,49 kn
//       ja-JP: ¥1,603.49
open System.Globalization

let cultureNames =
    [| "en-US"; "en-GB"; "fr-FR"; "hr-HR"; "ja-JP" |]
let value = 1603.49m
for cultureName in cultureNames do
    let culture = CultureInfo cultureName
    printfn $"""{culture.Name}: {value.ToString("C2", culture)}"""
// The example displays the following output:
//       en-US: $1,603.49
//       en-GB: £1,603.49
//       fr-FR: 1 603,49 €
//       hr-HR: 1.603,49 kn
//       ja-JP: ¥1,603.49
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "en-GB", "fr-FR",
                                       "hr-HR", "ja-JP" }
      Dim value As Decimal = 1603.49d
      For Each cultureName In cultureNames
         Dim culture As New CultureInfo(cultureName)
         Console.WriteLine("{0}: {1}", culture.Name,
                           value.ToString("C2", culture))
      Next
   End Sub
End Module
' The example displays the following output:
'       en-US: $1,603.49
'       en-GB: £1,603.49
'       fr-FR: 1 603,49 €
'       hr-HR: 1.603,49 kn
'       ja-JP: ¥1,603.49

서식 문자열 및 문화권 구분 서식에 대한 자세한 내용은 형식 서식 지정을 참조하세요. 숫자 값에서 지원하는 형식 문자열은 표준 숫자 서식 문자열 및사용자 지정 숫자 서식 문자열을 참조하세요. 날짜 및 시간 값에서 지원하는 형식 문자열은 표준 날짜 및 시간 서식 문자열 및사용자 지정 날짜 및 시간 서식 문자열을 참조하세요.

Object.ToString 메서드 확장

형식은 기본 Object.ToString 메서드를 상속하므로 해당 동작이 바람직하지 않고 변경할 수 있습니다. 배열 및 컬렉션 클래스의 경우 특히 그렇습니다. 배열 또는 컬렉션 클래스의 메서드가 해당 멤버의 값을 표시할 것으로 예상 ToString 할 수 있지만 다음 예제와 같이 형식이 정규화된 형식 이름을 대신 표시합니다.

int[] values = { 1, 2, 4, 8, 16, 32, 64, 128 };
Console.WriteLine(values.ToString());

List<int> list = new List<int>(values);
Console.WriteLine(list.ToString());

// The example displays the following output:
//       System.Int32[]
//       System.Collections.Generic.List`1[System.Int32]
let values = [| 1; 2; 4; 8; 16; 32; 64; 128 |]
printfn $"{values}"

let list = ResizeArray values
printfn $"{list}"

// The example displays the following output:
//       System.Int32[]
//       System.Collections.Generic.List`1[System.Int32]
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim values() As Integer = { 1, 2, 4, 8, 16, 32, 64, 128 }
      Console.WriteLine(values.ToString())
      
      Dim list As New List(Of Integer)(values)
      Console.WriteLine(list.ToString())
   End Sub
End Module
' The example displays the following output:
'    System.Int32[]
'    System.Collections.Generic.List`1[System.Int32]

원하는 결과 문자열을 생성하는 몇 가지 옵션이 있습니다.

  • 형식이 배열, 컬렉션 개체 또는 또는 IEnumerable<T> 인터페이스를 구현 IEnumerable 하는 개체인 경우 C#의 문 또는 For Each...Next Visual Basic의 foreach 구문을 사용하여 해당 요소를 열거할 수 있습니다.

  • 클래스가 (C#) 또는 NotInheritable (Visual Basic의 경우)이 아니면 sealed 메서드를 사용자 지정할 기본 클래스에서 상속되는 Object.ToString 래퍼 클래스를 개발할 수 있습니다. 최소한 다음을 수행해야 합니다.

    1. 필요한 생성자를 구현합니다. 파생 클래스는 기본 클래스 생성자를 상속하지 않습니다.

    2. 메서드를 재정의 Object.ToString 하여 원하는 결과 문자열을 반환합니다.

    다음 예제에서는 클래스에 대 한 래퍼 클래스를 정의 합니다 List<T> . 정규화된 형식 이름이 아닌 컬렉션의 각 메서드 값을 표시하도록 메서드를 재정 Object.ToString 의합니다.

    using System;
    using System.Collections.Generic;
    
    public class CList<T> : List<T>
    {
       public CList(IEnumerable<T> collection) : base(collection)
       { }
    
       public CList() : base()
       {}
    
       public override string ToString()
       {
          string retVal = string.Empty;
          foreach (T item in this) {
             if (string.IsNullOrEmpty(retVal))
                retVal += item.ToString();
             else
                retVal += string.Format(", {0}", item);
          }
          return retVal;
       }
    }
    
    public class Example
    {
       public static void Main()
       {
          var list2 = new CList<int>();
          list2.Add(1000);
          list2.Add(2000);
          Console.WriteLine(list2.ToString());
       }
    }
    // The example displays the following output:
    //    1000, 2000
    
    open System
    open System.Collections.Generic
    
    type CList<'T>() = 
        inherit ResizeArray<'T>()
        
        override this.ToString() =
            let mutable retVal = String.Empty
            for item in this do
                if String.IsNullOrEmpty retVal then
                    retVal <- retVal + string item
                else
                    retVal <- retVal + $", {item}"
            retVal
    
    let list2 = CList()
    list2.Add 1000
    list2.Add 2000
    printfn $"{list2}"
    // The example displays the following output:
    //    1000, 2000
    
    Imports System.Collections.Generic
    
    Public Class CList(Of T) : Inherits List(Of T)
       Public Sub New(capacity As Integer)
          MyBase.New(capacity)
       End Sub
    
       Public Sub New(collection As IEnumerable(Of T))
          MyBase.New(collection)
       End Sub
    
       Public Sub New()
          MyBase.New()
       End Sub
    
       Public Overrides Function ToString() As String
          Dim retVal As String = String.Empty
          For Each item As T In Me
             If String.IsNullOrEmpty(retval) Then
                retVal += item.ToString()
             Else
                retval += String.Format(", {0}", item)
             End If
          Next
          Return retVal
       End Function
    End Class
    
    Module Example
       Public Sub Main()
          Dim list2 As New CList(Of Integer)
          list2.Add(1000)
          list2.Add(2000)
          Console.WriteLine(list2.ToString())
       End Sub
    End Module
    ' The example displays the following output:
    '       1000, 2000
    
  • 원하는 결과 문자열을 반환하는 확장 메서드 를 개발합니다. 이러한 방식으로 기본 Object.ToString 메서드를 재정의할 수 없습니다(즉, 확장 클래스(C#) 또는 모듈(Visual Basic의 경우)은 원래 형식의 ToString 메서드 대신 호출되는 매개 ToString 변수 없는 메서드를 사용할 수 없습니다. 매개 변수 없는 ToString 대체에 대한 다른 이름을 제공해야 합니다.

    다음 예제에서는 클래스를 확장하는 List<T> 두 가지 메서드인 매개 변수 없는 ToString2 메서드와 ToString 형식 문자열을 String 나타내는 매개 변수가 있는 메서드를 정의합니다.

    using System;
    using System.Collections.Generic;
    
    public static class StringExtensions
    {
       public static string ToString2<T>(this List<T> l)
       {
          string retVal = string.Empty;
          foreach (T item in l)
             retVal += string.Format("{0}{1}", string.IsNullOrEmpty(retVal) ?
                                                         "" : ", ",
                                      item);
          return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }";
       }
    
       public static string ToString<T>(this List<T> l, string fmt)
       {
          string retVal = string.Empty;
          foreach (T item in l) {
             IFormattable ifmt = item as IFormattable;
             if (ifmt != null)
                retVal += string.Format("{0}{1}",
                                        string.IsNullOrEmpty(retVal) ?
                                           "" : ", ", ifmt.ToString(fmt, null));
             else
                retVal += ToString2(l);
          }
          return string.IsNullOrEmpty(retVal) ? "{}" : "{ " + retVal + " }";
       }
    }
    
    public class Example
    {
       public static void Main()
       {
          List<int> list = new List<int>();
          list.Add(1000);
          list.Add(2000);
          Console.WriteLine(list.ToString2());
          Console.WriteLine(list.ToString("N0"));
       }
    }
    // The example displays the following output:
    //       { 1000, 2000 }
    //       { 1,000, 2,000 }
    
    open System
    open System.Collections.Generic
    
    type List<'T> with
        member this.ToString2<'T>() = 
            let mutable retVal = String.Empty
            for item in this do
               retVal <- retVal + $"""{if String.IsNullOrEmpty retVal then "" else ", "}{item}"""
            if String.IsNullOrEmpty retVal then "{}" else "{ " + retVal + " }"
    
        member this.ToString<'T>(fmt: string) =
            let mutable retVal = String.Empty
            for item in this do
                match box item with
                | :? IFormattable as ifmt ->
                    retVal <- retVal + $"""{if String.IsNullOrEmpty retVal then "" else ", "}{ifmt.ToString(fmt, null)}"""
                | _ ->
                    retVal <- retVal + this.ToString2()
            if String.IsNullOrEmpty retVal then "{}" else "{ " + retVal + " }"
    
    let list = ResizeArray()
    list.Add 1000
    list.Add 2000
    printfn $"{list.ToString2()}"
    printfn $"""{list.ToString "N0"}"""
    // The example displays the following output:
    //       { 1000, 2000 }
    //       { 1,000, 2,000 }
    
    Imports System.Collections.Generic
    Imports System.Runtime.CompilerServices
    
    Public Module StringExtensions
       <Extension()>
       Public Function ToString2(Of T)(l As List(Of T)) As String
          Dim retVal As String = ""
          For Each item As T In l
             retVal += String.Format("{0}{1}", If(String.IsNullOrEmpty(retVal),
                                                         "", ", "),
                                      item)
          Next
          Return If(String.IsNullOrEmpty(retVal), "{}", "{ " + retVal + " }")
       End Function
    
       <Extension()>
       Public Function ToString(Of T)(l As List(Of T), fmt As String) As String
          Dim retVal As String = String.Empty
          For Each item In l
             Dim ifmt As IFormattable = TryCast(item, IFormattable)
             If ifmt IsNot Nothing Then
                retVal += String.Format("{0}{1}",
                                        If(String.IsNullOrEmpty(retval),
                                           "", ", "), ifmt.ToString(fmt, Nothing))
             Else
                retVal += ToString2(l)
             End If
          Next
          Return If(String.IsNullOrEmpty(retVal), "{}", "{ " + retVal + " }")
       End Function
    End Module
    
    Module Example
       Public Sub Main()
          Dim list As New List(Of Integer)
          list.Add(1000)
          list.Add(2000)
          Console.WriteLine(list.ToString2())
          Console.WriteLine(list.ToString("N0"))
       End Sub
    End Module
    ' The example displays the following output:
    '       { 1000, 2000 }
    '       { 1,000, 2,000 }
    

Windows 런타임 대한 참고 사항

Windows 런타임 클래스에서 메서드를 호출 ToString 할 때 재정의하지 ToString않는 클래스에 대한 기본 동작을 제공합니다. 이는 .NET Framework Windows 런타임 제공하는 지원의 일부입니다(Windows 스토어 앱 및 Windows 런타임 .NET Framework 지원 참조). Windows 런타임 클래스는 를 상속Object하지 않으며 항상 를 ToString구현하지는 않습니다. 그러나 C# 또는 Visual Basic 코드에서 사용할 때 항상 , Equals(Object)GetHashCode 메서드가 있는 것처럼 보이며 ToString.NET Framework 이러한 메서드에 대한 기본 동작을 제공합니다.

.NET Framework 4.5.1부터 공용 언어 런타임은 의 기본 구현Object.ToString으로 돌아가기 전에 Windows 런타임 개체에서 IStringable.ToString을 사용합니다.

참고

C# 또는 Visual Basic으로 작성된 Windows 런타임 클래스는 메서드를 재정의할 ToString 수 있습니다.

Windows 런타임 및 IStringable 인터페이스

Windows 8.1 시작하여 Windows 런타임 단일 메서드인 IStringable.ToString이 에서 제공하는 Object.ToString것과 비슷한 기본 서식 지원을 제공하는 IStringable 인터페이스를 포함합니다. 모호성을 방지하려면 관리되는 형식에서 IStringable을 구현하면 안 됩니다.

관리되는 개체가 네이티브 코드 또는 JavaScript 또는 C++/CX와 같은 언어로 작성된 코드로 호출되는 경우 IStringable을 구현하는 것처럼 보입니다. 공용 언어 런타임은 IStringable.ToString 의 호출을 Object.ToString 관리되는 개체에서 IStringable 이 구현되지 않은 경우 로 자동으로 라우팅합니다.

경고

공용 언어 런타임은 Windows 스토어 앱의 모든 관리되는 형식에 대해 IStringable 을 자동으로 구현하므로 고유한 IStringable 구현을 제공하지 않는 것이 좋습니다. 를 구현하면 IStringable Windows 런타임, C++/CX 또는 JavaScript에서 를 호출 ToString 할 때 의도하지 않은 동작이 발생할 수 있습니다.

Windows 런타임 구성 요소에서 내보낸 공용 관리형 형식에서 IStringable을 구현하도록 선택하는 경우 다음 제한이 적용됩니다.

  • 다음과 같이 "클래스 구현" 관계에서만 IStringable 인터페이스를 정의할 수 있습니다.

    public class NewClass : IStringable
    
    Public Class NewClass : Implements IStringable
    
  • 인터페이스에서 IStringable 을 구현할 수 없습니다.

  • 매개 변수를 IStringable 형식으로 선언할 수 없습니다.

  • IStringable 은 메서드, 속성 또는 필드의 반환 형식일 수 없습니다.

  • 다음과 같은 메서드 정의를 사용하여 기본 클래스에서 IStringable 구현을 숨길 수 없습니다.

    
    public class NewClass : IStringable  
    {  
       public new string ToString()  
       {  
          return "New ToString in NewClass";  
       }  
    }  
    
    

    대신 합니다 IStringable.ToString 구현은 언제나 기본 클래스 구현을 재지정 해야 합니다. 강력한 형식의 ToString 클래스 instance 호출해야만 구현을 숨길 수 있습니다.

다양한 조건에서 네이티브 코드에서 IStringable 을 구현하거나 ToString 구현을 숨기는 관리되는 형식으로 호출하면 예기치 않은 동작이 발생할 수 있습니다.

상속자 참고

고유한 형식을 구현하는 경우 메서드를 재정의 ToString() 하여 해당 형식에 의미 있는 값을 반환해야 합니다. 제공보다 ToString() 서식을 더 많이 제어해야 하는 파생 클래스는 인터페이스를 구현할 IFormattable 수 있습니다. 해당 ToString(String, IFormatProvider) 메서드를 사용하면 서식을 제어하는 형식 문자열을 정의하고 문화권별 서식을 제공할 수 있는 개체를 사용할 IFormatProvider 수 있습니다.

메서드의 재정의는 ToString() 다음 지침을 따라야 합니다.

  • 반환된 문자열은 인간에게 친숙하고 읽을 수 있어야 합니다.

  • 반환된 문자열은 개체 instance 값을 고유하게 식별해야 합니다.

  • 반환된 문자열은 디버거에서 표시하는 데 적합할 수 있도록 가능한 한 짧아야 합니다.

  • ToString() 재정의는 또는 null 문자열을 반환 Empty 해서는 안 됩니다.

  • ToString() 재정의는 예외를 throw해서는 안 됩니다.

  • instance 문자열 표현이 문화권을 구분하거나 여러 가지 방법으로 서식을 지정할 수 있는 경우 인터페이스를 구현합니다IFormattable.

  • 반환된 문자열에 중요한 정보가 포함된 경우 먼저 적절한 권한을 요구해야 합니다. 요청이 성공하면 중요한 정보를 반환할 수 있습니다. 그렇지 않으면 중요한 정보를 제외하는 문자열을 반환해야 합니다.

  • ToString() 재정의는 디버깅에 합병증을 피하기 위해 관찰 가능한 부작용이 없어야 합니다. 예를 들어 메서드를 호출하면 ToString() instance 필드의 값이 변경되지 않아야 합니다.

  • 형식이 구문 분석 메서드(또는 ParseTryParse 메서드, 생성자 또는 문자열에서 형식의 instance 인스턴스화하는 다른 정적 메서드)를 구현하는 경우 메서드에서 반환 ToString() 된 문자열을 개체 instance 변환할 수 있는지 확인해야 합니다.

적용 대상

추가 정보