Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Método Object.ToString ()

 

Publicado: agosto de 2016

Retorna uma string que representa o objeto atual.

Namespace:   System
Assembly:  mscorlib (em mscorlib.dll)

public virtual string ToString()

Valor Retornado

Type: System.String

Uma cadeia de caracteres que representa o objeto atual.

Object.ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in the .NET Framework, see Formatando tipos no .NET Framework.) Default implementations of the Object.ToString method return the fully qualified name of the object's type.

System_CAPS_importantImportante

You may have reached this page by following the link from the member list of another type. That is because that type does not override M:System.Object.ToString. Instead, it inherits the functionality of the M:System.Object.ToString method.

Types frequently override the M:System.Object.ToString method to provide a more suitable string representation of a particular type. Types also frequently overload the M:System.Object.ToString method to provide support for format strings or culture-sensitive formatting.

In this section:

The default Object.ToString() method
Overriding the Object.ToString() method
Overloading the ToString method
Extending the Object.ToString method
Notes for the Windows Runtime

The default implementation of the M:System.Object.ToString method returns the fully qualified name of the type of the T:System.Object, as the following example shows.

using System;

public class Example
{
   public static void Main()
   {
      Object obj = new Object();
      Console.WriteLine(obj.ToString());
   }
}
// The example displays the following output:
//      System.Object

Because T:System.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 M:System.Object.ToString method. The following example illustrates this. It defines a class named Object1 that accepts the default implementation of all T:System.Object members. Its M:System.Object.ToString method returns the object's fully qualified type name.

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

Types commonly override the M:System.Object.ToString method to return a string that represents the object instance. For example, the base types such as T:System.Char, T:System.Int32, and T:System.String provide M:System.Object.ToString implementations that return the string form of the value that the object represents. The following example defines a class, Object2, that overrides the M:System.Object.ToString method to return the type name along with its value.

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

The following table lists the type categories in the .NET Framework and indicates whether or not they override the M:System.Object.ToString method.

Type category

Overrides Object.ToString()

Behavior

Class

n/a

n/a

Structure

Yes (M:System.ValueType.ToString)

Same as Object.ToString()

Enumeration

Yes (M:System.Enum.ToString)

The member name

Interface

No

n/a

Delegate

No

n/a

See the Notes to Inheritors section for additional information on overriding M:System.Object.ToString.

In addition to overriding the parameterless M:System.Object.ToString method, many types overload the ToString method to provide versions of the method that accept parameters. Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.

The following example overloads the ToString method to return a result string that includes the value of various fields of an Automobile class. 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

The following example calls the overloaded M:System.Decimal.ToString(System.String,System.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

For more information on format strings and culture-sensitive formatting, see Formatting Types. For the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. For the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

Because a type inherits the default M:System.Object.ToString method, you may find its behavior undesirable and want to change it. This is particularly true of arrays and collection classes. 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.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      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]

You have several options to produce the result string that you'd like.

  • If the type is an array, a collection object, or an object that implements the T:System.Collections.IEnumerable or T:System.Collections.Generic.IEnumerable`1 interfaces, you can enumerate its elements by using the foreach statement in C# or the For Each...Next construct in Visual Basic.

  • If the class is not sealed (in C#) or NotInheritable (in Visual Basic), you can develop a wrapper class that inherits from the base class whose M:System.Object.ToString method you want to customize. At a minimum, this requires that you do the following:

    1. Implement any necessary constructors. Derived classes do not inherit their base class constructors.

    2. Override the M:System.Object.ToString method to return the result string that you'd like.

    The following example defines a wrapper class for the T:System.Collections.Generic.List`1 class. It overrides the M:System.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
    
  • Develop an extension method that returns the result string that you want. Note that you can't override the default M:System.Object.ToString method in this way (that is, your extension class (in C#) or module (in Visual Basic) cannot have a parameterless method named ToString that is called in place of the original type's ToString method. You'll have to provide some other name for your parameterless ToString replacement.

    The following example defines two methods that extend the T:System.Collections.Generic.List`1 class: a parameterless ToString2 method, and a ToString method with a T:System.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 }
    

When you call the M:System.Object.ToString method on a class in the wrt, it provides the default behavior for classes that don’t override M:System.Object.ToString. This is part of the support that the .NET Framework provides for the wrt (see .NET Framework Support for Windows Store Apps and Windows Runtime). Classes in the wrt don’t inherit T:System.Object, and don’t always implement a M:System.Object.ToString. However, they always appear to have M:System.Object.ToString, M:System.Object.Equals(System.Object), and M:System.Object.GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides a default behavior for these methods.

Starting with the net_v451, the common language runtime will use IStringable.ToStringhttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx on a wrt object before falling back to the default implementation of M:System.Object.ToString.

System_CAPS_noteObservação

Tempo de Execução do Windows classes that are written in C# or Visual Basic can override the ToString method.

Starting with win81, the wrt includes an IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx interface whose single method, IStringable.ToStringhttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx, provides basic formatting support comparable to that provided by M:System.Object.ToString. To prevent ambiguity, you should not implement IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx on managed types.

When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx. The common language runtime will automatically route calls from IStringable.ToStringhttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx to M:System.Object.ToString in the event IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx is not implemented on the managed object.

System_CAPS_warningAviso

Because the common language runtime auto-implements IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx for all managed types in win8_appstore_long apps, we recommend that you do not provide your own IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx implementation. Implementing IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx may result in unintended behavior when calling ToString from the wrt, C++/CX, or JavaScript.

If you do choose to implement IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx in a public managed type that is exported in a wrt component, the following restrictions apply:

  • You can define the IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx interface only in a "class implements" relationship, such as

    public class NewClass : IStringable
    

    in C#, or

    Public Class NewClass : Implements IStringable
    

    in Visual Basic.

  • You cannot implement IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx on an interface.

  • You cannot declare a parameter to be of type IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx.

  • IStringable cannot be the return type of a method, property, or field.

  • You cannot hide your IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx 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";
       }
    }
    
    

    Instead, the IStringable.ToStringhttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx implementation must always override the base class implementation. You can hide a ToString implementation only by invoking it on a strongly typed class instance.

Note that under a variety of conditions, calls from native code to a managed type that implements IStringablehttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.aspx or hides its ToStringhttp://msdn.microsoft.com/library/windows/apps/windows.foundation.istringable.tostring.aspx implementation can produce unexpected behavior.

Observações para os Herdeiros:

When you implement your own types, you should override the M:System.Object.ToString method to return values that are meaningful for those types. Derived classes that require more control over formatting than M:System.Object.ToString provides can implement the T:System.IFormattable interface. Its M:System.IFormattable.ToString(System.String,System.IFormatProvider) method enables you to define format strings that control formatting and to use an T:System.IFormatProvider object that can provide for culture-specific formatting.

Overrides of the M:System.Object.ToString method should follow these guidelines:

  • The returned string should be friendly and readable by humans.

  • The returned string should uniquely identify the value of the object instance.

  • The returned string should be as short as possible so that it is suitable for display by a debugger.

  • Your M:System.Object.ToString override should not return F:System.String.Empty or a null string.

  • Your M:System.Object.ToString override should not throw an exception.

  • If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the T:System.IFormattable interface.

  • If the returned string includes sensitive information, you should first demand an appropriate permission. If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.

  • Your M:System.Object.ToString override should have no observable side effects to avoid complications in debugging. For example, a call to the M:System.Object.ToString method should not change the value of instance fields.

  • 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 M:System.Object.ToString method can be converted to an object instance.

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1
Retornar ao início
Mostrar: