이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.
Object.ToString 는 .NET의 일반적인 서식 지정 메서드입니다. 표시에 적합하도록 개체를 문자열 표현으로 변환합니다. (.NET의 서식 지원에 대한 자세한 내용은 형식 서식 지정을 참조하세요.) 메서드의 Object.ToString 기본 구현은 개체 형식의 정규화된 이름을 반환합니다.
중요합니다
다른 유형의 멤버 목록에서 링크를 따라 이 페이지에 도달했을 수 있습니다. 해당 유형이 Object.ToString을(를) 오버라이드하지 않기 때문입니다. 대신 메서드의 Object.ToString 기능을 상속합니다.
형식은 특정 형식의 Object.ToString 보다 적합한 문자열 표현을 제공하기 위해 메서드를 재정의하는 경우가 많습니다. 형식은 메서드 Object.ToString를 오버로드하여 형식 문자열이나 문화권 구분 서식 지정을 지원하는 경우가 많습니다.
기본 Object.ToString() 메서드
메서드의 ToString 기본 구현은 다음 예제에서 보여주는 것처럼 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 Example3
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의 모든 참조 형식의 기본 클래스이므로, ToString 메서드를 재정의하지 않는 참조 형식에 의해 이 동작이 상속됩니다. 다음 예제에서는 이를 보여 줍니다. 모든 Object1
멤버의 기본 구현을 허용하는 명명된 Object 클래스를 정의합니다. 해당 메서드는 ToString 개체의 정규화된 형식 이름을 반환합니다.
using System;
using Examples;
namespace Examples
{
public class Object1
{
}
}
public class Example5
{
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
Public Class Object1
End Class
Module Example4
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 나타내는 문자열을 반환하도록 메서드를 재정의합니다. 예를 들어, Char, Int32, 및 String와 같은 기본 형식은 개체가 나타내는 값의 문자열 형식을 반환하는 ToString 구현을 제공합니다. 다음 예제에서는 Object2
메서드를 재정의하여 해당 값과 함께 형식 이름을 반환하도록 하는 클래스 ToString 를 정의합니다.
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 Example6
{
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 Example5
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()을 재정의합니다. | 행동 |
---|---|---|
클래스 | n/a | n/a |
구조 | 예(ValueType.ToString) |
Object.ToString() 동일 |
열거 | 예(Enum.ToString()) | 멤버 이름 |
인터페이스 | 아니오 | n/a |
대리인 | 아니오 | n/a |
상속자에 대한 참고 섹션에서 ToString 오버라이딩에 대한 추가 정보를 참조하세요.
ToString 메서드 오버로드
매개 변수 없는 Object.ToString() 메서드를 재정의하는 것 외에도 많은 형식이 ToString
메서드를 오버로드하여 매개 변수를 허용하는 메서드의 버전을 제공합니다. 가장 일반적으로 이 작업은 변수 서식 지정 및 문화권 구분 서식을 지원하기 위해 수행됩니다.
다음 예제에서는 ToString
메서드를 오버로드하여 Automobile
클래스의 다양한 필드 값을 포함하는 결과 문자열을 반환합니다. 모델 이름과 연도를 반환하는 4개의 형식 문자열인 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 Example7
{
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 Example6
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 Example8
{
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($"{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 Example7
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 및 IEnumerable<T> 인터페이스를 구현하는 개체인 경우 C#의
foreach
문 또는 Visual Basic의For Each...Next
구문을 사용하여 해당 요소를 열거할 수 있습니다.클래스가
sealed
(C#) 또는NotInheritable
(Visual Basic) 형식이 아닌 경우, 메서드를 사용자 정의하려는 기본 클래스를 상속하는 Object.ToString 래퍼 클래스를 개발할 수 있습니다. 최소한 다음을 수행해야 합니다.- 필요한 생성자를 구현합니다. 파생 클래스는 기본 클래스 생성자를 상속하지 않습니다.
- 원하는 결과 문자열을 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 Example2 { 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 Example1 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 Example3 { 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 Example2 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이 Windows 런타임에 대해 제공하는 지원의 일부입니다( Windows 스토어 앱 및 Windows 런타임에 대한 .NET 지원 참조). Windows 런타임의 클래스는 Object을(를) 상속하지 않으며, 항상 ToString을(를) 구현하는 것도 아닙니다. 그러나 C# 또는 Visual Basic 코드에서 사용할 때 항상 해당 메서드와 ToString 메서드가 있는 것처럼 보이며 Equals(Object)GetHashCode.NET은 이러한 메서드에 대한 기본 동작을 제공합니다.
공용 언어 런타임은 Windows 런타임 개체에서 IStringable.ToString을 사용한 후에 Object.ToString의 기본 구현으로 되돌아갑니다.
비고
C# 또는 Visual Basic으로 작성된 Windows 런타임 클래스는 ToString 메서드를 재정의할 수 있습니다.
Windows 런타임 및 IStringable 인터페이스
Windows 런타임에는 단일 메서드인 IStringable.ToString이 제공하는 것과 비슷한 기본 서식 지원을 제공하는 IStringable 인터페이스가 Object.ToString포함되어 있습니다. 모호성을 방지하기 위해 관리되는 형식에서 IStringable을 구현해서는 안 됩니다.
관리되는 개체가 네이티브 코드 또는 JavaScript 또는 C++/CX와 같은 언어로 작성된 코드로 호출되면 IStringable을 구현하는 것처럼 보입니다. 공용 언어 런타임은 IStringable이 관리 개체에 구현되지 않은 경우 Object.ToString에서 로 호출을 자동으로 라우팅합니다.
경고
공용 언어 런타임은 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
클래스 인스턴스에서 구현을 호출해야만 구현을 숨길 수 있습니다.
다양한 조건에서 네이티브 코드에서 관리되는 형식으로 호출하면, 해당 형식이 IStringable을 구현하거나 ToString 구현을 숨길 경우, 예기치 않은 동작이 발생할 수 있습니다.
.NET