Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Este artigo fornece comentários complementares à documentação de referência para esta API.
Object.ToString é um método de formatação comum no .NET. Ele converte um objeto em sua representação de cadeia de caracteres para que ele seja adequado para exibição. (Para obter informações sobre o suporte à formatação no .NET, consulte Tipos de Formatação.) As implementações padrão do Object.ToString método retornam o nome totalmente qualificado do tipo do objeto.
Importante
Você pode ter acessado esta página seguindo o link da lista de membros de outro tipo. Isso ocorre porque esse tipo não substitui Object.ToString. Em vez disso, herda a funcionalidade do Object.ToString método.
Os tipos frequentemente substituem o Object.ToString método para fornecer uma representação de cadeia de caracteres mais adequada de um tipo específico. Os tipos também costumam sobrecarregar o método Object.ToString para dar suporte a cadeias de caracteres de formato ou a formatação sensível à cultura.
O método Object.ToString() padrão
A implementação padrão do método ToString retorna o nome totalmente qualificado do tipo do Object, como mostra o exemplo a seguir.
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
Como Object é a classe base de todos os tipos de referência no .NET, esse comportamento é herdado por tipos de referência que não substituem o ToString método. O exemplo a seguir ilustra essa situação. Ele define uma classe nomeada Object1 que aceita a implementação padrão de todos os Object membros. Seu ToString método retorna o nome de tipo totalmente qualificado do objeto.
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
Sobrescrever o método Object.ToString()
Os tipos geralmente substituem o Object.ToString método para retornar uma cadeia de caracteres que representa a instância do objeto. Por exemplo, os tipos base, como Char, Int32e String fornecem ToString implementações que retornam a forma de cadeia de caracteres do valor que o objeto representa. O exemplo a seguir define uma classe, Object2que substitui o ToString método para retornar o nome do tipo junto com seu valor.
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
A tabela a seguir lista as categorias de tipo no .NET e indica se elas substituem ou não o Object.ToString método.
| Categoria de tipo | Substitui Object.ToString() | Comportamento |
|---|---|---|
| Classe | Não disponível | Não disponível |
| Estrutura | Sim (ValueType.ToString) | O mesmo que Object.ToString() |
| Enumeração | Sim (Enum.ToString()) | O nome do membro |
| Interfase | Não | Não disponível |
| Delegar | Não | Não disponível |
Consulte a seção Anotações para Herdeiros para obter informações adicionais sobre como substituir ToString.
Sobrecarregar o método ToString
Além de substituir o método Object.ToString() sem parâmetros, muitos tipos sobrecarregam o método ToString para fornecer versões do método que aceitam parâmetros. Geralmente, isso é feito para dar suporte à formatação variável e à formatação sensível à cultura.
O exemplo a seguir sobrecarrega o ToString método para retornar uma cadeia de caracteres de resultado que inclui o valor de vários campos de uma Automobile classe. Ele define quatro cadeias de caracteres de formato: G, que retorna o nome do modelo e o ano; D, que retorna o nome do modelo, o ano e o número de portas; C, que retorna o nome do modelo, o ano e o número de cilindros; e A, que retorna uma cadeia de caracteres com todos os quatro valores de campo.
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
O exemplo a seguir chama o método sobrecarregado Decimal.ToString(String, IFormatProvider) para exibir a formatação sensível à cultura de um valor de moeda.
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
Para obter mais informações sobre cadeias de caracteres de formato e formatação sensível à cultura, consulte Tipos de Formatação. Para as cadeias de caracteres de formato compatíveis com valores numéricos, consulte Cadeias de Caracteres de Formato Numérico Padrão e Cadeias de Caracteres de Formato Numérico Personalizado. Para as cadeias de caracteres de formato compatíveis com valores de data e hora, consulte Cadeias de caracteres de formato de data e hora padrão e cadeias de caracteres de formato de data e hora personalizadas.
Estender o método Object.ToString
Como um tipo herda o método padrão Object.ToString , você pode achar seu comportamento indesejável e desejar alterá-lo. Isso é particularmente verdadeiro para matrizes e classes de coleções. Embora você possa esperar que o método ToString de uma matriz ou classe de coleção exiba os valores dos membros, em vez disso, ele exibe o nome de tipo completo, como mostra o exemplo a seguir.
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]
Existem várias opções para produzir o texto de resultado que deseja.
Se o tipo for uma matriz, um objeto de coleção ou um objeto que implementa o IEnumerable ou IEnumerable<T> interfaces, você poderá enumerar seus elementos usando a
foreachinstrução em C# ou oFor Each...Nextconstructo no Visual Basic.Se a classe não for
sealed(em C#) ouNotInheritable(no Visual Basic), você pode desenvolver uma classe wrapper que herda da classe base e cujo método Object.ToString você deseja personalizar. No mínimo, isso requer que você faça o seguinte:- Implemente todos os construtores necessários. Classes derivadas não herdam seus construtores de classe base.
- Sobrescreva o método Object.ToString para retornar a string de resultado desejada.
O exemplo a seguir define uma classe wrapper para a List<T> classe. Ele substitui o Object.ToString método para exibir o valor de cada método da coleção em vez do nome de tipo totalmente qualificado.
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, 2000open 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, 2000Imports 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, 2000Desenvolva um método de extensão que retorna a cadeia de caracteres de resultado desejada. Observe que você não pode substituir o método padrão Object.ToString dessa maneira, ou seja, sua classe de extensão (em C#) ou módulo (no Visual Basic) não pode ter um método sem parâmetros chamado
ToStringno lugar do método doToStringtipo original. Você precisará fornecer um outro nome para a substituição sem parâmetros deToString.O exemplo a seguir define dois métodos que estendem a List<T> classe: um método sem
ToString2parâmetros e umToStringmétodo com um String parâmetro que representa uma cadeia de caracteres de formato.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 }
Anotações para o Windows Runtime
Quando você chama o ToString método em uma classe no Windows Runtime, ele fornece o comportamento padrão para classes que não substituem ToString. Isso faz parte do suporte que o .NET fornece para o Windows Runtime (consulte o suporte do .NET para aplicativos da Windows Store e o Windows Runtime). As classes no Windows Runtime não herdam Object e não implementam sempre uma ToString. No entanto, eles sempre parecem ter ToString, Equals(Object)e GetHashCode métodos quando você os usa em seu código C# ou Visual Basic, e o .NET fornece um comportamento padrão para esses métodos.
O runtime de linguagem comum usa IStringable.ToString em um objeto do Windows Runtime antes de voltar à implementação padrão de Object.ToString.
Observação
As classes do Windows Runtime escritas em C# ou Visual Basic podem substituir o ToString método.
O Windows Runtime e a interface IStringable
O Windows Runtime inclui uma interface IStringable cujo único método, IStringable.ToString, fornece suporte de formatação básica comparável ao fornecido por Object.ToString. Para evitar ambiguidade, você não deve implementar IStringable em tipos gerenciados.
Quando objetos gerenciados são chamados por código nativo ou por código escrito em linguagens como JavaScript ou C++/CX, eles parecem implementar IStringable. O common language runtime roteia automaticamente chamadas de IStringable.ToString para Object.ToString se IStringable não for implementado no objeto gerenciado.
Aviso
Como o runtime de linguagem comum implementa automaticamente IStringable para todos os tipos gerenciados em aplicativos da Windows Store, recomendamos que você não forneça sua própria implementação de IStringable. A implementação IStringable pode resultar em um comportamento não intencional ao chamar ToString do Windows Runtime, C++/CX ou JavaScript.
Se você optar por implementar o IStringable em um tipo gerenciado público exportado em um componente do Windows Runtime, as seguintes restrições se aplicam:
Você pode definir a interface IStringable apenas em uma relação de "implementações de classe", da seguinte maneira:
public class NewClass : IStringablePublic Class NewClass : Implements IStringableVocê não pode implementar iStringable em uma interface.
Você não pode declarar um parâmetro como do tipo IStringable.
IStringable não pode ser o tipo de retorno de um método, propriedade ou campo.
Você não pode ocultar sua implementação IStringable de classes base usando uma definição de método, como a seguinte:
public class NewClass : IStringable { public new string ToString() { return "New ToString in NewClass"; } }Em vez disso, a implementação IStringable.ToString deve sempre sobrescrever a implementação da classe base. Você pode ocultar uma implementação de
ToStringinvocando-a apenas em uma instância da classe fortemente tipada.
Sob uma variedade de condições, chamadas de código nativo para um tipo gerenciado que implementa IStringable ou oculta sua implementação de ToString podem produzir um comportamento inesperado.