Object.ToString Méthode
Définition
Retourne une chaîne qui représente l'objet actuel.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
Retours
Chaîne qui représente l'objet actuel.A string that represents the current object.
Remarques
Object.ToString est la méthode de mise en forme principale de la .NET Framework.Object.ToString is the major formatting method in the .NET Framework. Il convertit un objet en sa représentation sous forme de chaîne afin qu’il soit adapté à l’affichage.It converts an object to its string representation so that it is suitable for display. (Pour plus d’informations sur la prise en charge de la mise en forme dans le .NET Framework, consultez mise en forme des types.) Les implémentations par défaut de la Object.ToString méthode retournent le nom qualifié complet du type de l’objet.(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.
Important
Vous avez peut-être atteint cette page en suivant le lien de la liste des membres d’un autre type.You may have reached this page by following the link from the member list of another type. Cela est dû au fait que ce type ne substitue pas Object.ToString .That is because that type does not override Object.ToString. Au lieu de cela, elle hérite des fonctionnalités de la Object.ToString méthode.Instead, it inherits the functionality of the Object.ToString method.
Les types se substituent fréquemment Object.ToString à la méthode pour fournir une représentation sous forme de chaîne plus appropriée d’un type particulier.Types frequently override the Object.ToString method to provide a more suitable string representation of a particular type. Les types surchargent également fréquemment la Object.ToString méthode pour fournir la prise en charge des chaînes de format ou de la mise en forme dépendante de la culture.Types also frequently overload the Object.ToString method to provide support for format strings or culture-sensitive formatting.
Dans cette section :In this section:
Méthode Object. ToString () par défaut The default Object.ToString() method
Substitution de la méthode Object. ToString () Overriding the Object.ToString() method
Surcharge de la méthode ToString Overloading the ToString method
Extension de la méthode Object. ToString Extending the Object.ToString method
Notes pour le Windows RuntimeNotes for the Windows Runtime
Méthode Object. ToString () par défautThe default Object.ToString() method
L’implémentation par défaut de la ToString méthode retourne le nom qualifié complet du type de Object , comme le montre l’exemple suivant.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
Étant donné que Object est la classe de base de tous les types référence dans le .NET Framework, ce comportement est hérité par les types référence qui ne substituent pas la ToString méthode.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. L'exemple suivant illustre ce comportement.The following example illustrates this. Il définit une classe nommée Object1
qui accepte l’implémentation par défaut de tous les Object membres.It defines a class named Object1
that accepts the default implementation of all Object members. Sa ToString méthode retourne le nom de type qualifié complet de l’objet.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
Substitution de la méthode Object. ToString ()Overriding the Object.ToString() method
Les types remplacent généralement la Object.ToString méthode pour retourner une chaîne qui représente l’instance d’objet.Types commonly override the Object.ToString method to return a string that represents the object instance. Par exemple, les types de base tels que Char , Int32 et String fournissent des ToString implémentations qui retournent la forme de chaîne de la valeur représentée par l’objet.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. L’exemple suivant définit une classe, Object2
, qui substitue la ToString méthode pour retourner le nom du type avec sa valeur.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
Le tableau suivant répertorie les catégories de types dans .NET et indique si elles substituent ou non la Object.ToString méthode.The following table lists the type categories in .NET and indicates whether or not they override the Object.ToString method.
Catégorie de typeType category | Remplace Object. ToString ()Overrides Object.ToString() | ComportementBehavior |
---|---|---|
ClasseClass | n/an/a | n/an/a |
StructureStructure | Oui ( ValueType.ToString )Yes (ValueType.ToString) | Identique à Object.ToString() Same as Object.ToString() |
ÉnumérationEnumeration | Oui ( Enum.ToString() )Yes (Enum.ToString()) | Nom du membreThe member name |
InterfaceInterface | NonNo | n/an/a |
DéléguéDelegate | NonNo | n/an/a |
Pour plus d’informations sur la substitution, consultez la section Remarques à l’héritage ToString .See the Notes to Inheritors section for additional information on overriding ToString.
Surcharge de la méthode ToStringOverloading the ToString method
Outre la substitution de la méthode sans paramètre Object.ToString() , de nombreux types surchargent la ToString
méthode pour fournir des versions de la méthode qui acceptent des paramètres.In addition to overriding the parameterless Object.ToString() method, many types overload the ToString
method to provide versions of the method that accept parameters. La plupart du temps, cette opération est effectuée pour assurer la prise en charge de la mise en forme variable et de la mise en forme dépendante de la culture.Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.
L’exemple suivant surcharge la ToString
méthode pour retourner une chaîne de résultat qui comprend la valeur de divers champs d’une 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. Il définit quatre chaînes de format : G, qui retourne le nom du modèle et l’année ; D, qui retourne le nom du modèle, l’année et le nombre de portes ; C, qui retourne le nom du modèle, l’année et le nombre de cylindres ; et, qui retourne une chaîne avec les quatre valeurs de champ.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
L’exemple suivant appelle la méthode surchargée Decimal.ToString(String, IFormatProvider) pour afficher la mise en forme dépendante de la culture d’une valeur monétaire.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
Pour plus d’informations sur les chaînes de format et la mise en forme dépendante de la culture, consultez mise en forme des types.For more information on format strings and culture-sensitive formatting, see Formatting Types. Pour les chaînes de format prises en charge par les valeurs numériques, consultez chaînes de format numériques standard et chaînes de format numériques personnalisées.For the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Pour les chaînes de format prises en charge par les valeurs de date et d’heure, consultez chaînes de format de date et d’heure standard et chaînes de format de date et d’heure personnalisées.For the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Extension de la méthode Object. ToStringExtending the Object.ToString method
Étant donné qu’un type hérite de la méthode par défaut Object.ToString , son comportement peut ne pas être souhaitable et doit être modifié.Because a type inherits the default Object.ToString method, you may find its behavior undesirable and want to change it. Cela est particulièrement vrai pour les classes de collection et les tableaux.This is particularly true of arrays and collection classes. Vous pouvez vous attendre à ce que la ToString
méthode d’un tableau ou d’une classe de collection affiche les valeurs de ses membres. elle affiche à la place le nom de type complet du type, comme le montre l’exemple suivant.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]
Vous avez plusieurs options pour produire la chaîne de résultat que vous souhaitez.You have several options to produce the result string that you'd like.
Si le type est un tableau, un objet de collection ou un objet qui implémente les IEnumerable IEnumerable<T> interfaces ou, vous pouvez énumérer ses éléments à l’aide de l'
foreach
instruction en C# ou de laFor Each...Next
construction dans 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 classe n’est pas
sealed
(en C#) ouNotInheritable
(dans Visual Basic), vous pouvez développer une classe wrapper qui hérite de la classe de base dont Object.ToString vous souhaitez personnaliser la méthode.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. Au minimum, vous devez effectuer les opérations suivantes :At a minimum, this requires that you do the following:Implémentez les constructeurs nécessaires.Implement any necessary constructors. Les classes dérivées n’héritent pas de leurs constructeurs de classe de base.Derived classes do not inherit their base class constructors.
Substituez la Object.ToString méthode pour retourner la chaîne de résultat que vous souhaitez.Override the Object.ToString method to return the result string that you'd like.
L’exemple suivant définit une classe wrapper pour la List<T> classe.The following example defines a wrapper class for the List<T> class. Elle substitue la Object.ToString méthode pour afficher la valeur de chaque méthode de la collection plutôt que le nom de type qualifié complet.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
Développez une méthode d’extension qui retourne la chaîne de résultat souhaitée.Develop an extension method that returns the result string that you want. Notez que vous ne pouvez pas substituer la méthode par défaut Object.ToString de cette manière (autrement dit, votre classe d’extension (en C#) ou le module (dans Visual Basic) ne peut pas avoir une méthode sans paramètre nommée
ToString
qui est appelée à la place de la méthode du type d’origineToString
.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. Vous devrez fournir un autre nom pour votre remplacement sans paramètreToString
.You'll have to provide some other name for your parameterlessToString
replacement.L’exemple suivant définit deux méthodes qui étendent la List<T> classe : une méthode sans paramètre
ToString2
et uneToString
méthode avec un String paramètre qui représente une chaîne de format.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 }
Notes pour le Windows RuntimeWindows RuntimeNotes for the Windows RuntimeWindows Runtime
Quand vous appelez la ToString méthode sur une classe dans le Windows RuntimeWindows Runtime , elle fournit le comportement par défaut pour les classes qui ne remplacent pas 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. Il s’agit d’une partie de la prise en charge fournie par le .NET Framework pour Windows RuntimeWindows Runtime (consultez .NET Framework prise en charge des applications et Windows Runtime du Windows Store).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). Les classes dans le Windows RuntimeWindows Runtime n’héritent pas Object et n’implémentent pas toujours un ToString .Classes in the Windows RuntimeWindows Runtime don't inherit Object, and don't always implement a ToString. Toutefois, ils semblent toujours avoir des ToString Equals(Object) méthodes, et GetHashCode lorsque vous les utilisez dans votre code C# ou Visual Basic, et le .NET Framework fournit un comportement par défaut pour ces méthodes.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.
À compter de .NET Framework 4.5.1.NET Framework 4.5.1 , le Common Language Runtime utilise IStringable. ToString sur un Windows RuntimeWindows Runtime objet avant de revenir à l’implémentation par défaut 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.
Notes
Windows RuntimeWindows Runtime les classes écrites en C# ou Visual Basic peuvent substituer la ToString méthode.classes that are written in C# or Visual Basic can override the ToString method.
Windows RuntimeWindows RuntimeEt l’interface IStringableThe Windows RuntimeWindows Runtime and the IStringable Interface
À partir de Windows 8.1Windows 8.1 , Windows RuntimeWindows Runtime inclut une interface IStringable dont la méthode unique, IStringable. ToString, fournit une prise en charge de la mise en forme de base comparable à celle fournie par 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. Pour éviter toute ambiguïté, vous ne devez pas implémenter IStringable sur les types managés.To prevent ambiguity, you should not implement IStringable on managed types.
Lorsque des objets managés sont appelés par du code natif ou par du code écrit dans des langages tels que JavaScript ou C++/CX, ils semblent implémenter 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. Le common language runtime achemine automatiquement les appels de IStringable. ToString vers Object.ToString si IStringable n’est pas implémenté sur l’objet managé.The common language runtime automatically routes calls from IStringable.ToString to Object.ToString if IStringable is not implemented on the managed object.
Avertissement
Étant donné que le common language runtime implémente automatiquement IStringable pour tous les types managés dans les Windows StoreWindows Store applications, nous vous recommandons de ne pas fournir votre propre IStringable
implémentation.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. IStringable
L’implémentation de peut entraîner un comportement inattendu lors ToString
de l’appel de 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.
Si vous choisissez d’implémenter IStringable dans un type managé public qui est exporté dans un Windows RuntimeWindows Runtime composant, les restrictions suivantes s’appliquent :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:
Vous pouvez définir l’interface IStringable uniquement dans une relation « classe Implements », comme suit :You can define the IStringable interface only in a "class implements" relationship, as follows:
public class NewClass : IStringable
Public Class NewClass : Implements IStringable
Vous ne pouvez pas implémenter IStringable sur une interface.You cannot implement IStringable on an interface.
Vous ne pouvez pas déclarer un paramètre de type IStringable.You cannot declare a parameter to be of type IStringable.
IStringable ne peut pas être le type de retour d’une méthode, d’une propriété ou d’un champ.IStringable cannot be the return type of a method, property, or field.
Vous ne pouvez pas masquer votre implémentation IStringable à partir des classes de base à l’aide d’une définition de méthode telle que la suivante :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"; } }
Au lieu de cela, l’implémentation de IStringable. ToString doit toujours remplacer l’implémentation de la classe de base.Instead, the IStringable.ToString implementation must always override the base class implementation. Vous pouvez masquer une implémentation
ToString
uniquement en l'appelant sur une instance de classe fortement typée.You can hide aToString
implementation only by invoking it on a strongly typed class instance.
Notez que dans diverses conditions, les appels de code natif à un type managé qui implémente IStringable ou masquent son implémentation ToString peuvent entraîner un comportement inattendu.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.
Notes pour les héritiers
Quand vous implémentez vos propres types, vous devez substituer la ToString() méthode pour retourner des valeurs qui sont significatives pour ces types.When you implement your own types, you should override the ToString() method to return values that are meaningful for those types. Les classes dérivées qui requièrent davantage de contrôle sur la mise en forme que ToString() ne peuvent implémenter l' IFormattable interface.Derived classes that require more control over formatting than ToString() provides can implement the IFormattable interface. Sa ToString(String, IFormatProvider) méthode vous permet de définir des chaînes de format qui contrôlent la mise en forme et d’utiliser un IFormatProvider objet pouvant fournir une mise en forme spécifique à la culture.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.
Les substitutions de la ToString() méthode doivent respecter les instructions suivantes :Overrides of the ToString() method should follow these guidelines: -La chaîne retournée doit être conviviale et lisible par les êtres humains.- The returned string should be friendly and readable by humans.
-La chaîne retournée doit identifier de manière unique la valeur de l’instance d’objet.- The returned string should uniquely identify the value of the object instance.
-La chaîne retournée doit être aussi petite que possible pour pouvoir être affichée par un débogueur.- The returned string should be as short as possible so that it is suitable for display by a debugger.
-Votre ToString() substitution ne doit pas retourner Empty ou une chaîne NULL.- Your ToString() override should not return Empty or a null string.
-Votre ToString() substitution ne doit pas lever d’exception.- Your ToString() override should not throw an exception.
-Si la représentation sous forme de chaîne d’une instance est dépendante de la culture ou peut être mise en forme de plusieurs façons, implémentez l' IFormattable interface.- If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the IFormattable interface.
-Si la chaîne retournée contient des informations sensibles, vous devez d’abord demander une autorisation appropriée.- If the returned string includes sensitive information, you should first demand an appropriate permission. Si la demande est réussie, vous pouvez retourner les informations sensibles. dans le cas contraire, vous devez retourner une chaîne qui exclut les informations sensibles.If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.
-Votre ToString() substitution ne doit pas avoir d’effets secondaires observables afin d’éviter des complications lors du débogage.- Your ToString() override should have no observable side effects to avoid complications in debugging. Par exemple, un appel à la ToString() méthode ne doit pas modifier la valeur des champs d’instance.For example, a call to the ToString() method should not change the value of instance fields.
-Si votre type implémente une méthode d’analyse (ou Parse
TryParse
une méthode, un constructeur ou une autre méthode statique qui instancie une instance du type à partir d’une chaîne), vous devez vous assurer que la chaîne retournée par la ToString() méthode peut être convertie en instance d’objet.- 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.