Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
MSDN
MSDN Library
System
 ToString (Método)
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
Object..::.ToString Method

Updated: March 2011

Returns a string that represents the current object.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
Public Overridable Function ToString As String
C#
public virtual string ToString()
Visual C++
public:
virtual String^ ToString()
F#
abstract ToString : unit -> string 
override ToString : unit -> string 

Return Value

Type: System..::.String
A string that represents the current 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 Formatting Types.)

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

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

Visual Basic
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
C#
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 ToString method to return a string that represents the object instance. 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. The following example defines a class, Object2, that overrides the ToString method to return the type name along with its value.

Visual Basic
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
C#
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

Notes to Implementers

When you implement your own types, you should override the ToString method to return values that are meaningful for those types. Derived classes that require more control over formatting than ToString provides can implement the IFormattable interface. Its IFormattable..::.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.

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Date

History

Reason

March 2011

Revised extensively.

Customer feedback.

Biblioteca de clases de .NET Framework
Object..::.ToString (Método)

Devuelve una cadena que representa el objeto actual.

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)
Visual Basic
Public Overridable Function ToString As String
C#
public virtual string ToString()
Visual C++
public:
virtual String^ ToString()
F#
abstract ToString : unit -> string 
override ToString : unit -> string 

Valor devuelto

Tipo: System..::.String
Cadena que representa el objeto actual.

ToString es el método de formato primario en .NET Framework. Convierte un objeto en su representación de cadena para que sea conveniente para la presentación. (Para obtener más información sobre compatibilidad de formatos en .NET Framework, vea Aplicar formato a tipos.)

La implementación predeterminada del método ToString devuelve el nombre completo del tipo de Object, como se muestra en el ejemplo siguiente.

Visual Basic
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
C#
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

Dado que Object es la clase base de todos los tipos de referencia en .NET Framework, este comportamiento hereda tipos de referencia que no invalidan el método ToString. Esto se puede ver en el ejemplo siguiente. Define una clase denominada Object1 que acepta la implementación predeterminada de todos los miembros Object. Su método ToString devuelve el nombre de tipo completo del objeto.

Visual Basic
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
C#
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

Los tipos invalidan normalmente el método ToString para devolver una cadena que representa la instancia de objeto. Por ejemplo, los tipos base tales como Char, Int32 y String proporcionan implementaciones de ToString que devuelven el formato de cadena del valor que representa el objeto. En el siguiente ejemplo se define una clase, Object2, que invalida el método ToString para devolver el nombre de tipo junto con su valor.

Visual Basic
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
C#
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

Notas para los implementadores

Al implementar sus propios tipos, debería invalidar el método ToString a los valores devueltos que son significativos para esos tipos. Las clases derivadas que requieren más control sobre cómo dar formato que el proporciona ToString pueden implementar la interfaz IFormattable. Su método IFormattable..::.ToString(String, IFormatProvider) permite definir cadenas de formato que controlan el formato y utilizar un objeto IFormatProvider que puede proporcionar el formato específico de la referencia cultural.

.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Fecha

Historial

Motivo

Marzo de 2011

Se ha revisado exhaustivamente.

Comentarios de los clientes.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker