Object.ToString Método
Definición
Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.
public:
virtual System::String ^ ToString();
public virtual string ToString ();
abstract member ToString : unit -> string
override this.ToString : unit -> string
Public Overridable Function ToString () As String
Devoluciones
Una cadena que representa el objeto actual.A string that represents the current object.
Comentarios
Object.ToString es el método de formato principal en el .NET Framework.Object.ToString is the major formatting method in the .NET Framework. Convierte un objeto en su representación de cadena para que sea adecuado para su presentación.It converts an object to its string representation so that it is suitable for display. (Para obtener información sobre la compatibilidad de formato en el .NET Framework, vea aplicar formato a tipos). Las implementaciones predeterminadas del Object.ToString método devuelven el nombre completo del tipo del 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
Es posible que haya llegado a esta página siguiendo el vínculo de la lista de miembros de otro tipo.You may have reached this page by following the link from the member list of another type. Esto se debe a que ese tipo no invalida Object.ToString .That is because that type does not override Object.ToString. En su lugar, hereda la funcionalidad del Object.ToString método.Instead, it inherits the functionality of the Object.ToString method.
Normalmente, los tipos invalidan el Object.ToString método para proporcionar una representación de cadena más adecuada de un tipo determinado.Types frequently override the Object.ToString method to provide a more suitable string representation of a particular type. Los tipos también sobrecargan con frecuencia el Object.ToString método para proporcionar compatibilidad con las cadenas de formato o el formato dependiente de la referencia cultural.Types also frequently overload the Object.ToString method to provide support for format strings or culture-sensitive formatting.
En esta sección:In this section:
El método Object. ToString () predeterminado The default Object.ToString() method
Reemplazar el método Object. ToString () Overriding the Object.ToString() method
Sobrecargar el método ToString Overloading the ToString method
Extender el método Object. ToString Extending the Object.ToString method
Notas del Windows RuntimeNotes for the Windows Runtime
El método Object. ToString () predeterminadoThe default Object.ToString() method
La implementación predeterminada del ToString método devuelve el nombre completo del tipo de Object , como se muestra en el ejemplo siguiente.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
Dado Object que es la clase base de todos los tipos de referencia en el .NET Framework, este comportamiento lo heredan los tipos de referencia que no invalidan el 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. Esto se ilustra en el siguiente ejemplo:The following example illustrates this. Define una clase denominada Object1
que acepta la implementación predeterminada de todos los Object miembros.It defines a class named Object1
that accepts the default implementation of all Object members. Su ToString método devuelve el nombre de tipo completo del 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
Reemplazar el método Object. ToString ()Overriding the Object.ToString() method
Normalmente, los tipos invalidan el Object.ToString método para devolver una cadena que representa la instancia del objeto.Types commonly override the Object.ToString method to return a string that represents the object instance. Por ejemplo, los tipos base como Char , Int32 y String proporcionan ToString implementaciones que devuelven la forma de cadena del valor que representa el objeto.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. En el ejemplo siguiente se define una clase, Object2
, que invalida el ToString método para devolver el nombre de tipo junto con su 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
En la tabla siguiente se enumeran las categorías de tipos de .NET y se indica si invalidan o no el Object.ToString método.The following table lists the type categories in .NET and indicates whether or not they override the Object.ToString method.
Categoría de tipoType category | Invalida Object. ToString ()Overrides Object.ToString() | ComportamientoBehavior |
---|---|---|
ClaseClass | N/Dn/a | N/Dn/a |
EstructuraStructure | Sí ( ValueType.ToString )Yes (ValueType.ToString) | Igual que Object.ToString() .Same as Object.ToString() |
EnumeraciónEnumeration | Sí ( Enum.ToString() )Yes (Enum.ToString()) | Nombre del miembroThe member name |
InterfazInterface | NoNo | N/Dn/a |
DelegadoDelegate | NoNo | N/Dn/a |
Vea la sección Notas para herederos para obtener información adicional sobre cómo reemplazar ToString .See the Notes to Inheritors section for additional information on overriding ToString.
Sobrecargar el método ToStringOverloading the ToString method
Además de invalidar el método sin parámetros Object.ToString() , muchos tipos sobrecargan el ToString
método para proporcionar versiones del método que aceptan 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, esto se hace para proporcionar compatibilidad con el formato de variables y el formato dependiente de la referencia cultural.Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.
En el ejemplo siguiente se sobrecarga el ToString
método para devolver una cadena de resultado que incluye el valor de varios campos de una Automobile
clase.The following example overloads the ToString
method to return a result string that includes the value of various fields of an Automobile
class. Define cuatro cadenas de formato: G, que devuelve el nombre del modelo y el año; D, que devuelve el nombre del modelo, el año y el número de puertas; C, que devuelve el nombre del modelo, el año y el número de cilindros; y, que devuelve una cadena con los cuatro 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
En el ejemplo siguiente se llama al método sobrecargado Decimal.ToString(String, IFormatProvider) para mostrar el formato dependiente de la referencia cultural de un valor de moneda.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 obtener más información sobre las cadenas de formato y el formato dependiente de la referencia cultural, vea aplicar formato a tipos.For more information on format strings and culture-sensitive formatting, see Formatting Types. Para las cadenas de formato admitidas por los valores numéricos, vea cadenas de formato numérico estándar y cadenas de formato numérico personalizado.For the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Para las cadenas de formato admitidas por los valores de fecha y hora, vea cadenas con formato de fecha y hora estándar y cadenas con formato de fecha y hora personalizado.For the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Extender el método Object. ToStringExtending the Object.ToString method
Dado que un tipo hereda el Object.ToString método predeterminado, es posible que el comportamiento no sea deseable y desee cambiarlo.Because a type inherits the default Object.ToString method, you may find its behavior undesirable and want to change it. Esto es especialmente cierto en el caso de las matrices y las clases de colección.This is particularly true of arrays and collection classes. Aunque puede esperar que el ToString
método de una matriz o clase de colección muestre los valores de sus miembros, en su lugar muestra el tipo nombre completo del tipo, como se muestra en el ejemplo siguiente.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]
Tiene varias opciones para generar la cadena de resultado que desee.You have several options to produce the result string that you'd like.
Si el tipo es una matriz, un objeto de colección o un objeto que implementa las IEnumerable interfaces o IEnumerable<T> , puede enumerar sus elementos mediante la
foreach
instrucción de C# o laFor Each...Next
construcción en 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.Si la clase no es
sealed
(en C#) oNotInheritable
(en Visual Basic), puede desarrollar una clase contenedora que herede de la clase base cuyo Object.ToString método desea 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. Como mínimo, debe hacer lo siguiente:At a minimum, this requires that you do the following:Implemente los constructores necesarios.Implement any necessary constructors. Las clases derivadas no heredan sus constructores de clase base.Derived classes do not inherit their base class constructors.
Invalide el Object.ToString método para devolver la cadena de resultado que desea.Override the Object.ToString method to return the result string that you'd like.
En el ejemplo siguiente se define una clase contenedora para la List<T> clase.The following example defines a wrapper class for the List<T> class. Invalida el Object.ToString método para mostrar el valor de cada método de la colección en lugar del nombre de tipo completo.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
Desarrolle un método de extensión que devuelva la cadena de resultado que desee.Develop an extension method that returns the result string that you want. Tenga en cuenta que no puede invalidar el Object.ToString método predeterminado de esta manera (es decir, su clase de extensión (en C#) o módulo (en Visual Basic) no puede tener un método sin parámetros denominado al
ToString
que se llama en lugar del método del 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. Tendrá que proporcionar otro nombre para su reemplazo sin parámetrosToString
.You'll have to provide some other name for your parameterlessToString
replacement.En el ejemplo siguiente se definen dos métodos que extienden la List<T> clase: un método sin parámetros
ToString2
y unToString
método con un String parámetro que representa una cadena 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 }
Notas del Windows en tiempo de ejecuciónWindows RuntimeNotes for the Windows en tiempo de ejecuciónWindows Runtime
Cuando se llama al ToString método en una clase en Windows en tiempo de ejecuciónWindows Runtime , proporciona el comportamiento predeterminado para las clases que no se invalidan ToString .When you call the ToString method on a class in the Windows en tiempo de ejecuciónWindows Runtime, it provides the default behavior for classes that don't override ToString. Esto forma parte de la compatibilidad que el .NET Framework proporciona para el Windows en tiempo de ejecuciónWindows Runtime (vea la compatibilidad de .NET Framework con las aplicaciones de la tienda Windows y Windows Runtime).This is part of the support that the .NET Framework provides for the Windows en tiempo de ejecuciónWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Las clases de Windows en tiempo de ejecuciónWindows Runtime no heredan Object y no siempre implementan ToString .Classes in the Windows en tiempo de ejecuciónWindows Runtime don't inherit Object, and don't always implement a ToString. Sin embargo, siempre parecen tener ToString Equals(Object) los métodos, y GetHashCode cuando se usan en el código de C# o Visual Basic, y el .NET Framework proporciona un comportamiento predeterminado para estos 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.
A partir de .NET Framework 4.5.1.NET Framework 4.5.1 , el Common Language Runtime utiliza IStringable. ToString en un Windows en tiempo de ejecuciónWindows Runtime objeto antes de revertir a la implementación predeterminada 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 en tiempo de ejecuciónWindows Runtime object before falling back to the default implementation of Object.ToString.
Nota
Windows en tiempo de ejecuciónWindows Runtime las clases escritas en C# o Visual Basic pueden invalidar el ToString método.classes that are written in C# or Visual Basic can override the ToString method.
Windows en tiempo de ejecuciónWindows RuntimeY la interfaz IStringableThe Windows en tiempo de ejecuciónWindows Runtime and the IStringable Interface
A partir de Windows 8.1Windows 8.1 , Windows en tiempo de ejecuciónWindows Runtime incluye una interfaz IStringable cuyo único método, IStringable. ToString, proporciona compatibilidad de formato básica comparable a la proporcionada por Object.ToString .Starting with Windows 8.1Windows 8.1, the Windows en tiempo de ejecuciónWindows Runtime includes an IStringable interface whose single method, IStringable.ToString, provides basic formatting support comparable to that provided by Object.ToString. Para evitar ambigüedades, no debe implementar IStringable en tipos administrados.To prevent ambiguity, you should not implement IStringable on managed types.
Cuando se llama a objetos administrados mediante código nativo o mediante código escrito en lenguajes como JavaScript o C++/CX, parecen implementar IStringable.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. El Common Language Runtime enruta automáticamente las llamadas de IStringable. ToString a Object.ToString si IStringable no está implementado en el objeto administrado.The common language runtime automatically routes calls from IStringable.ToString to Object.ToString if IStringable is not implemented on the managed object.
Advertencia
Dado que el Common Language Runtime implementa automáticamente IStringable para todos los tipos administrados en las Tienda WindowsWindows Store aplicaciones, se recomienda no proporcionar su propia IStringable
implementación.Because the common language runtime auto-implements IStringable for all managed types in Tienda WindowsWindows Store apps, we recommend that you do not provide your own IStringable
implementation. IStringable
La implementación de puede dar lugar a un comportamiento imprevisto al llamar a ToString
desde Windows en tiempo de ejecuciónWindows Runtime , C++/CX o JavaScript.Implementing IStringable
may result in unintended behavior when calling ToString
from the Windows en tiempo de ejecuciónWindows Runtime, C++/CX, or JavaScript.
Si decide implementar IStringable en un tipo administrado público que se exporte en un Windows en tiempo de ejecuciónWindows Runtime componente de, se aplican las restricciones siguientes:If you do choose to implement IStringable in a public managed type that's exported in a Windows en tiempo de ejecuciónWindows Runtime component, the following restrictions apply:
Solo puede definir la interfaz IStringable en una relación "la clase implementa", como se indica a continuación:You can define the IStringable interface only in a "class implements" relationship, as follows:
public class NewClass : IStringable
Public Class NewClass : Implements IStringable
No se puede implementar IStringable en una interfaz.You cannot implement IStringable on an interface.
No se puede declarar un parámetro como de tipo IStringable.You cannot declare a parameter to be of type IStringable.
IStringable no puede ser el tipo de valor devuelto de un método, propiedad o campo.IStringable cannot be the return type of a method, property, or field.
No se puede ocultar la implementación de IStringable de las clases base mediante una definición de método como la siguiente: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"; } }
En su lugar, la implementación de IStringable. ToString debe invalidar siempre la implementación de la clase base.Instead, the IStringable.ToString implementation must always override the base class implementation. Solo puedes ocultar una implementación de
ToString
invocándola en una instancia de clase fuertemente tipada.You can hide aToString
implementation only by invoking it on a strongly typed class instance.
Tenga en cuenta que en una serie de condiciones, las llamadas de código nativo a un tipo administrado que implemente IStringable u oculte su implementación de ToString pueden producir un comportamiento 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 a los desarrolladores de herederos
Al implementar sus propios tipos, debe invalidar el ToString() método para devolver valores que sean significativos para esos tipos.When you implement your own types, you should override the ToString() method to return values that are meaningful for those types. Las clases derivadas que requieren más control sobre ToString() el formato que proporciona pueden implementar la IFormattable interfaz.Derived classes that require more control over formatting than ToString() provides can implement the IFormattable interface. Su ToString(String, IFormatProvider) método permite definir cadenas de formato que controlan el formato y utilizan un IFormatProvider objeto que puede proporcionar un formato específico de la referencia cultural.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.
Las invalidaciones del ToString() método deben seguir estas instrucciones:Overrides of the ToString() method should follow these guidelines: -La cadena devuelta debe ser descriptiva y legible para los usuarios.- The returned string should be friendly and readable by humans.
-La cadena devuelta debe identificar de forma única el valor de la instancia del objeto.- The returned string should uniquely identify the value of the object instance.
-La cadena devuelta debe ser lo más corta posible para que sea adecuada para que la muestre un depurador.- The returned string should be as short as possible so that it is suitable for display by a debugger.
-La ToString() invalidación no debe devolver Empty o una cadena nula.- Your ToString() override should not return Empty or a null string.
-La ToString() invalidación no debe producir una excepción.- Your ToString() override should not throw an exception.
-Si la representación de cadena de una instancia es dependiente de la referencia cultural o se le puede dar formato de varias maneras, implemente la IFormattable interfaz.- If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the IFormattable interface.
-Si la cadena devuelta incluye información confidencial, debe solicitar primero un permiso adecuado.- If the returned string includes sensitive information, you should first demand an appropriate permission. Si la demanda se realiza correctamente, puede devolver la información confidencial; de lo contrario, debe devolver una cadena que excluya la información confidencial.If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.
-La ToString() invalidación no debe tener efectos secundarios observables para evitar complicaciones en la depuración.- Your ToString() override should have no observable side effects to avoid complications in debugging. Por ejemplo, una llamada al ToString() método no debe cambiar el valor de los campos de instancia.For example, a call to the ToString() method should not change the value of instance fields.
-Si el tipo implementa un método de análisis (o Parse
un TryParse
método o un constructor, o algún otro método estático que cree instancias de una instancia del tipo a partir de una cadena), debe asegurarse de que la cadena devuelta por el ToString() método se puede convertir en una instancia 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.