Object.ToString Método
Definição
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.
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
Retornos
Uma cadeia de caracteres que representa o objeto atual.A string that represents the current object.
Comentários
Object.ToString é o método de formatação principal no .NET Framework.Object.ToString is the major formatting method in the .NET Framework. Ele converte um objeto em sua representação de cadeia de caracteres para que ele seja adequado para exibição.It converts an object to its string representation so that it is suitable for display. (Para obter informações sobre o suporte de formatação no .NET Framework, consulte tipos de formatação.) As implementações padrão do Object.ToString método retornam o nome totalmente qualificado do tipo do objeto.(For information about formatting support in the .NET Framework, see Formatting Types.) Default implementations of the Object.ToString method return the fully qualified name of the object's type.
Importante
Você pode ter chegado a esta página seguindo o link da lista de membros de outro tipo.You may have reached this page by following the link from the member list of another type. Isso ocorre porque esse tipo não é substituído Object.ToString .That is because that type does not override Object.ToString. Em vez disso, ele herda a funcionalidade do Object.ToString método.Instead, it inherits the functionality of the Object.ToString method.
Os tipos substituem frequentemente o Object.ToString método para fornecer uma representação de cadeia de caracteres mais adequada de um tipo específico.Types frequently override the Object.ToString method to provide a more suitable string representation of a particular type. Os tipos também sobrecarregam freqüentemente o Object.ToString método para fornecer suporte para cadeias de caracteres de formato ou formatação sensível à cultura.Types also frequently overload the Object.ToString method to provide support for format strings or culture-sensitive formatting.
Nesta seção:In this section:
O método padrão Object. ToString () The default Object.ToString() method
Substituindo o método Object. ToString () Overriding the Object.ToString() method
Sobrecarregando o método ToString Overloading the ToString method
Estendendo o método Object. ToString Extending the Object.ToString method
Observações para o Windows RuntimeNotes for the Windows Runtime
O método padrão Object. ToString ()The default Object.ToString() method
A implementação padrão do ToString método retorna o nome totalmente qualificado do tipo do Object , como mostra o exemplo a seguir.The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.
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
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
Como Object é a classe base de todos os tipos de referência na .NET Framework, esse comportamento é herdado por tipos de referência que não substituem o ToString método.Because Object is the base class of all reference types in the .NET Framework, this behavior is inherited by reference types that do not override the ToString method. O exemplo a seguir ilustra essa situação.The following example illustrates this. Ele define uma classe chamada Object1
que aceita a implementação padrão de todos os Object Membros.It defines a class named Object1
that accepts the default implementation of all Object members. Seu ToString método retorna o nome do tipo totalmente qualificado do objeto.Its ToString method returns the object's fully qualified type name.
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
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
Substituindo o método Object. ToString ()Overriding the Object.ToString() method
Os tipos normalmente substituem o Object.ToString método para retornar uma cadeia de caracteres que representa a instância do objeto.Types commonly override the Object.ToString method to return a string that represents the object instance. Por exemplo, os tipos base, como Char , Int32 e String fornecem ToString implementações que retornam a forma de cadeia de caracteres do valor que o objeto representa.For example, the base types such as Char, Int32, and String provide ToString implementations that return the string form of the value that the object represents. O exemplo a seguir define uma classe, Object2
, que substitui o ToString método para retornar o nome do tipo junto com seu valor.The following example defines a class, Object2
, that overrides the ToString method to return the type name along with its value.
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
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
A tabela a seguir lista as categorias de tipo no .NET e indica se elas substituem ou não o Object.ToString método.The following table lists the type categories in .NET and indicates whether or not they override the Object.ToString method.
Categoria do tipoType category | Substitui Object. ToString ()Overrides Object.ToString() | ComportamentoBehavior |
---|---|---|
ClasseClass | N/Dn/a | N/Dn/a |
EstruturaStructure | Sim ( ValueType.ToString )Yes (ValueType.ToString) | Mesmo que Object.ToString() Same as Object.ToString() |
EnumeraçãoEnumeration | Sim ( Enum.ToString() )Yes (Enum.ToString()) | O nome do membroThe member name |
InterfaceInterface | NãoNo | N/Dn/a |
DelegarDelegate | NãoNo | N/Dn/a |
Consulte a seção observações para herdeiros para obter informações adicionais sobre substituição ToString .See the Notes to Inheritors section for additional information on overriding ToString.
Sobrecarregando o método ToStringOverloading the ToString method
Além de substituir o método sem parâmetros Object.ToString() , muitos tipos sobrecarregam o ToString
método para fornecer versões do método que aceitam parâmetros.In addition to overriding the parameterless Object.ToString() method, many types overload the ToString
method to provide versions of the method that accept parameters. Normalmente, isso é feito para fornecer suporte para formatação de variáveis e formatação sensível à cultura.Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.
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.The following example overloads the ToString
method to return a result string that includes the value of various fields of an Automobile
class. 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 um, que retorna uma cadeia de caracteres com todos os quatro valores de campo.It defines four format strings: G, which returns the model name and year; D, which returns the model name, year, and number of doors; C, which returns the model name, year, and number of cylinders; and A, which returns a string with all four field values.
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
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
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.The following example calls the overloaded Decimal.ToString(String, IFormatProvider) method to display culture-sensitive formatting of a currency value.
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
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
Para obter mais informações sobre cadeias de caracteres de formato e formatação sensível à cultura, consulte Formatando tipos.For more information on format strings and culture-sensitive formatting, see Formatting Types. 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éricoFor the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Para as cadeias de caracteres de formato com suporte pelos valores de data e hora, consulte cadeias de formato padrão de data e hora e cadeias de caracteres de formato personalizado e de dataFor the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Estendendo o método Object. ToStringExtending the Object.ToString method
Como um tipo herda o Object.ToString método padrão, você pode achar seu comportamento indesejável e desejar alterá-lo.Because a type inherits the default Object.ToString method, you may find its behavior undesirable and want to change it. Isso é particularmente verdadeiro para matrizes e classes de coleção.This is particularly true of arrays and collection classes. Embora você possa esperar que o ToString
método de uma matriz ou classe de coleção exiba os valores de seus membros, em vez disso, ele exibe o tipo nome de tipo totalmente qualificado, como mostra o exemplo a seguir.While you may expect the ToString
method of an array or collection class to display the values of its members, it instead displays the type fully qualified type name, as the following example shows.
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]
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]
Você tem várias opções para produzir a cadeia de caracteres de resultado que deseja.You have several options to produce the result string that you'd like.
Se o tipo for uma matriz, um objeto de coleção ou um objeto que implementa as IEnumerable IEnumerable<T> interfaces ou, você poderá enumerar seus elementos usando a
foreach
instrução em C# ou aFor Each...Next
construção em Visual Basic.If the type is an array, a collection object, or an object that implements the IEnumerable or IEnumerable<T> interfaces, you can enumerate its elements by using theforeach
statement in C# or theFor Each...Next
construct in Visual Basic.Se a classe não for
sealed
(em C#) ouNotInheritable
(em Visual Basic), você poderá desenvolver uma classe wrapper que herde da classe base cujo Object.ToString método você deseja personalizar.If the class is notsealed
(in C#) orNotInheritable
(in Visual Basic), you can develop a wrapper class that inherits from the base class whose Object.ToString method you want to customize. No mínimo, isso requer que você faça o seguinte:At a minimum, this requires that you do the following:Implemente todos os construtores necessários.Implement any necessary constructors. Classes derivadas não herdam seus construtores de classe base.Derived classes do not inherit their base class constructors.
Substitua o Object.ToString método para retornar a cadeia de caracteres de resultado que você deseja.Override the Object.ToString method to return the result string that you'd like.
O exemplo a seguir define uma classe wrapper para a List<T> classe.The following example defines a wrapper class for the List<T> class. Ele substitui o Object.ToString método para exibir o valor de cada método da coleção em vez do nome do tipo totalmente qualificado.It overrides the Object.ToString method to display the value of each method of the collection rather than the fully qualified type name.
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
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
Desenvolva um método de extensão que retorne a cadeia de caracteres de resultado desejada.Develop an extension method that returns the result string that you want. Observe que você não pode substituir o Object.ToString método padrão dessa maneira (ou seja, sua classe de extensão (em C#) ou Module (em Visual Basic) não pode ter um método sem parâmetros chamado
ToString
que é chamado no lugar do método do tipo originalToString
.Note that you can't override the default Object.ToString method in this way (that is, your extension class (in C#) or module (in Visual Basic) cannot have a parameterless method namedToString
that is called in place of the original type'sToString
method. Você precisará fornecer algum outro nome para a substituição sem parâmetrosToString
.You'll have to provide some other name for your parameterlessToString
replacement.O exemplo a seguir define dois métodos que estendem a List<T> classe: um método sem parâmetros
ToString2
e umToString
método com um String parâmetro que representa uma cadeia de caracteres de formato.The following example defines two methods that extend the List<T> class: a parameterlessToString2
method, and aToString
method with a String parameter that represents a format 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 }
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 }
Observações para o Windows RuntimeWindows RuntimeNotes for the Windows RuntimeWindows Runtime
Quando você chama o ToString método em uma classe no Windows RuntimeWindows Runtime , ele fornece o comportamento padrão para classes que não substituem ToString .When you call the ToString method on a class in the Windows RuntimeWindows Runtime, it provides the default behavior for classes that don't override ToString. Isso faz parte do suporte que o .NET Framework fornece para o Windows RuntimeWindows Runtime (consulte suporte .NET Framework para aplicativos da Windows Store e Windows Runtime).This is part of the support that the .NET Framework provides for the Windows RuntimeWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). As classes em Windows RuntimeWindows Runtime não herdam Object e nem sempre implementam um ToString .Classes in the Windows RuntimeWindows Runtime don't inherit Object, and don't always implement a ToString. No entanto, eles sempre parecem ter ToString , Equals(Object) e GetHashCode métodos quando você os utiliza em seu código C# ou Visual Basic, e o .NET Framework fornece um comportamento padrão para esses métodos.However, they always appear to have ToString, Equals(Object), and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides a default behavior for these methods.
Começando com .NET Framework 4.5.1.NET Framework 4.5.1 o, o Common Language Runtime usa isastringable. ToString em um Windows RuntimeWindows Runtime objeto antes de fazer fallback para a implementação padrão de Object.ToString .Starting with .NET Framework 4.5.1.NET Framework 4.5.1, the common language runtime uses IStringable.ToString on a Windows RuntimeWindows Runtime object before falling back to the default implementation of Object.ToString.
Observação
Windows RuntimeWindows Runtime as classes escritas em C# ou Visual Basic podem substituir o ToString método.classes that are written in C# or Visual Basic can override the ToString method.
O Windows RuntimeWindows Runtime e a interface de IStringableThe Windows RuntimeWindows Runtime and the IStringable Interface
A partir Windows 8.1Windows 8.1 do, o Windows RuntimeWindows Runtime inclui uma interface isastringable cujo único método, isastringable. ToString, fornece suporte de formatação básica comparável ao fornecido pelo Object.ToString .Starting with Windows 8.1Windows 8.1, the Windows RuntimeWindows Runtime includes an IStringable interface whose single method, IStringable.ToString, provides basic formatting support comparable to that provided by Object.ToString. Para evitar ambigüidade, você não deve implementar isastringable em tipos gerenciados.To prevent ambiguity, you should not implement IStringable on managed types.
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 isastringable.When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement IStringable. O Common Language Runtime roteia automaticamente chamadas de isastringable. ToString para Object.ToString se isdeleble não estiver implementado no objeto gerenciado.The common language runtime automatically routes calls from IStringable.ToString to Object.ToString if IStringable is not implemented on the managed object.
Aviso
Como o Common Language Runtime implementa automaticamente isastringable para todos os tipos gerenciados em Windows StoreWindows Store aplicativos, recomendamos que você não forneça sua própria IStringable
implementação.Because the common language runtime auto-implements IStringable for all managed types in Windows StoreWindows Store apps, we recommend that you do not provide your own IStringable
implementation. A implementação IStringable
pode resultar em comportamento indesejado ao chamar ToString
do Windows RuntimeWindows Runtime , C++/CX ou JavaScript.Implementing IStringable
may result in unintended behavior when calling ToString
from the Windows RuntimeWindows Runtime, C++/CX, or JavaScript.
Se você optar por implementar isastringable em um tipo gerenciado público que é exportado em um Windows RuntimeWindows Runtime componente, as seguintes restrições serão aplicáveis:If you do choose to implement IStringable in a public managed type that's exported in a Windows RuntimeWindows Runtime component, the following restrictions apply:
Você pode definir a interface isastringable somente em uma relação de "classe implementa", da seguinte maneira:You can define the IStringable interface only in a "class implements" relationship, as follows:
public class NewClass : IStringable
Public Class NewClass : Implements IStringable
Não é possível implementar isastringable em uma interface.You cannot implement IStringable on an interface.
Você não pode declarar um parâmetro para ser do tipo isastringable.You cannot declare a parameter to be of type IStringable.
Isastringable não pode ser o tipo de retorno de um método, propriedade ou campo.IStringable cannot be the return type of a method, property, or field.
Não é possível ocultar sua implementação isastringable de classes base usando uma definição de método como a seguinte:You cannot hide your IStringable implementation from base classes by using a method definition such as the following:
public class NewClass : IStringable { public new string ToString() { return "New ToString in NewClass"; } }
Em vez disso, a implementação isastringable. ToString sempre deve substituir a implementação da classe base.Instead, the IStringable.ToString implementation must always override the base class implementation. Você pode ocultar uma implementação de
ToString
invocando-a apenas em uma instância da classe fortemente tipada.You can hide aToString
implementation only by invoking it on a strongly typed class instance.
Observe que, em uma variedade de condições, o chama de código nativo para um tipo gerenciado que implementa isastringable ou oculta sua implementação ToString pode produzir um comportamento inesperado.Note that under a variety of conditions, calls from native code to a managed type that implements IStringable or hides its ToString implementation can produce unexpected behavior.
Notas aos Herdeiros
Ao implementar seus próprios tipos, você deve substituir o ToString() método para retornar valores que são significativos para esses tipos.When you implement your own types, you should override the ToString() method to return values that are meaningful for those types. As classes derivadas que exigem mais controle sobre a formatação do que ToString() o fornece podem implementar a IFormattable interface.Derived classes that require more control over formatting than ToString() provides can implement the IFormattable interface. Seu ToString(String, IFormatProvider) método permite que você defina cadeias de caracteres de formato que controlam a formatação e usam um IFormatProvider objeto que pode fornecer formatação específica de cultura.Its ToString(String, IFormatProvider) method enables you to define format strings that control formatting and to use an IFormatProvider object that can provide for culture-specific formatting.
As substituições do ToString() método devem seguir estas diretrizes:Overrides of the ToString() method should follow these guidelines: -A cadeia de caracteres retornada deve ser amigável e legível por seres humanos.- The returned string should be friendly and readable by humans.
-A cadeia de caracteres retornada deve identificar exclusivamente o valor da instância do objeto.- The returned string should uniquely identify the value of the object instance.
-A cadeia de caracteres retornada deve ser a mais curta possível, de modo que seja adequada para exibição por um depurador.- The returned string should be as short as possible so that it is suitable for display by a debugger.
-Sua ToString() substituição não deve retornar Empty ou uma cadeia de caracteres nula.- Your ToString() override should not return Empty or a null string.
-Sua ToString() substituição não deve gerar uma exceção.- Your ToString() override should not throw an exception.
-Se a representação de cadeia de caracteres de uma instância for sensível à cultura ou puder ser formatada de várias maneiras, implemente a IFormattable interface.- If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the IFormattable interface.
-Se a cadeia de caracteres retornada incluir informações confidenciais, você deverá primeiro solicitar uma permissão apropriada.- If the returned string includes sensitive information, you should first demand an appropriate permission. Se a demanda for realizada com sucesso, você poderá retornar as informações confidenciais; caso contrário, você deve retornar uma cadeia de caracteres que exclui as informações confidenciais.If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.
-Sua ToString() substituição não deve ter efeitos colaterais observáveis para evitar complicações na depuração.- Your ToString() override should have no observable side effects to avoid complications in debugging. Por exemplo, uma chamada para o ToString() método não deve alterar o valor de campos de instância.For example, a call to the ToString() method should not change the value of instance fields.
-Se o seu tipo implementar um método de análise ( Parse
ou TryParse
, um construtor ou algum outro método estático que instancie uma instância do tipo a partir de uma cadeia de caracteres), você deverá garantir que a cadeia de caracteres retornada pelo ToString() método possa ser convertida em uma instância de objeto.- If your type implements a parsing method (or Parse
or TryParse
method, a constructor, or some other static method that instantiates an instance of the type from a string), you should ensure that the string returned by the ToString() method can be converted to an object instance.