Object.ToString Metodo
Definizione
Restituisce una stringa che rappresenta l'oggetto corrente.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
Restituisce
Stringa che rappresenta l'oggetto corrente.A string that represents the current object.
Commenti
Object.ToString è il metodo di formattazione principale nell'.NET Framework.Object.ToString is the major formatting method in the .NET Framework. Converte un oggetto nella relativa rappresentazione di stringa, in modo che sia adatto per la visualizzazione.It converts an object to its string representation so that it is suitable for display. Per informazioni sul supporto della formattazione nella .NET Framework, vedere formattazione di tipi. Le implementazioni predefinite del metodo Object.ToString restituiscono il nome completo del tipo dell'oggetto.(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
È possibile che la pagina sia stata raggiunta seguendo il collegamento dall'elenco dei membri di un altro tipo.You may have reached this page by following the link from the member list of another type. Ciò è dovuto al fatto che il tipo non esegue l'override Object.ToString.That is because that type does not override Object.ToString. Ma eredita la funzionalità del metodo Object.ToString.Instead, it inherits the functionality of the Object.ToString method.
I tipi spesso eseguono l'override del metodo Object.ToString per fornire una rappresentazione di stringa più adatta di un determinato tipo.Types frequently override the Object.ToString method to provide a more suitable string representation of a particular type. I tipi inoltre eseguono spesso l'overload del metodo Object.ToString per fornire supporto per le stringhe di formato o la formattazione dipendente dalle impostazioni cultura.Types also frequently overload the Object.ToString method to provide support for format strings or culture-sensitive formatting.
Nota
Alcuni degli esempi in C# in questo articolo vengono eseguiti nello strumento di esecuzione e playground per codice inline Try.NET.Some of the C# examples in this article run in the Try.NET inline code runner and playground. Quando è presente, selezionare il pulsante Esegui per eseguire un esempio in una finestra interattiva.When present, select the Run button to run an example in an interactive window. Dopo aver eseguito il codice, è possibile modificarlo ed eseguire il codice modificato selezionando di nuovo Esegui.Once you execute the code, you can modify it and run the modified code by selecting Run again. Il codice modificato viene eseguito nella finestra interattiva o, se la compilazione non riesce, la finestra interattiva visualizza tutti i messaggi di errore del compilatore C#.The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
Contenuto della sezione:In this section:
Il metodo Object. ToString () predefinito The default Object.ToString() method
Override del metodo Object. ToString () Overriding the Object.ToString() method
Overload del metodo ToString Overloading the ToString method
Estensione del metodo Object. ToString Extending the Object.ToString method
Note per il Windows RuntimeNotes for the Windows Runtime
Metodo Object. ToString () predefinitoThe default Object.ToString() method
L'implementazione predefinita del metodo ToString restituisce il nome completo del tipo di Object, come illustrato nell'esempio riportato di seguito.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
Poiché Object è la classe base di tutti i tipi di riferimento nel .NET Framework, questo comportamento viene ereditato dai tipi di riferimento che non eseguono l'override del metodo ToString.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. Ciò è illustrato nell'esempio seguente.The following example illustrates this. Definisce una classe denominata Object1
che accetta l'implementazione predefinita di tutti i membri Object.It defines a class named Object1
that accepts the default implementation of all Object members. Il metodo ToString restituisce il nome completo del tipo dell'oggetto.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
Override del metodo Object. ToString ()Overriding the Object.ToString() method
I tipi in genere eseguono l'override del metodo Object.ToString per restituire una stringa che rappresenta l'istanza dell'oggetto.Types commonly override the Object.ToString method to return a string that represents the object instance. I tipi di base, ad esempio Char, Int32e String, forniscono ToString implementazioni che restituiscono il formato stringa del valore rappresentato dall'oggetto.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. Nell'esempio seguente viene definita una classe, Object2
, che esegue l'override del metodo ToString per restituire il nome del tipo insieme al relativo valore.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
Nella tabella seguente sono elencate le categorie di tipi in .NET e viene indicato se eseguire l'override del metodo Object.ToString.The following table lists the type categories in .NET and indicates whether or not they override the Object.ToString method.
Categoria di tipiType category | Esegue l'override di Object. ToString ()Overrides Object.ToString() | ComportamentoBehavior |
---|---|---|
ClasseClass | N/Dn/a | N/Dn/a |
StrutturaStructure | Sì (ValueType.ToString)Yes (ValueType.ToString) | Uguale a Object.ToString() Same as Object.ToString() |
EnumerazioneEnumeration | Sì (Enum.ToString())Yes (Enum.ToString()) | Nome del membroThe member name |
InterfacciaInterface | NoNo | N/Dn/a |
DelegatoDelegate | NoNo | N/Dn/a |
Per ulteriori informazioni sull'override di ToString, vedere la sezione Note per gli eredi.See the Notes to Inheritors section for additional information on overriding ToString.
Overload del metodo ToStringOverloading the ToString method
Oltre a eseguire l'override del metodo Object.ToString() senza parametri, molti tipi eseguono l'overload del metodo ToString
per fornire versioni del metodo che accettano parametri.In addition to overriding the parameterless Object.ToString() method, many types overload the ToString
method to provide versions of the method that accept parameters. In genere, questa operazione viene eseguita per fornire supporto per la formattazione delle variabili e la formattazione dipendente dalle impostazioni cultura.Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.
Nell'esempio seguente viene sovraccarico il metodo ToString
per restituire una stringa di risultato che include il valore di diversi campi di una classe Automobile
.The following example overloads the ToString
method to return a result string that includes the value of various fields of an Automobile
class. Definisce quattro stringhe di formato: G, che restituisce il nome del modello e l'anno; D, che restituisce il nome del modello, l'anno e il numero di porte; C, che restituisce il nome del modello, l'anno e il numero di cilindri; e, che restituisce una stringa con tutti e quattro i valori di 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
Nell'esempio seguente viene chiamato il metodo di Decimal.ToString(String, IFormatProvider) di overload per visualizzare la formattazione dipendente dalle impostazioni cultura di un valore di valuta.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
Per ulteriori informazioni sulle stringhe di formato e sulla formattazione dipendente dalle impostazioni cultura, vedere formattazione di tipi.For more information on format strings and culture-sensitive formatting, see Formatting Types. Per le stringhe di formato supportate da valori numerici, vedere stringhe di formato numerico standard e stringhe di formato numerico personalizzate.For the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. Per le stringhe di formato supportate dai valori di data e ora, vedere stringhe di formato di data e ora standard e stringhe di formato di data e ora personalizzate.For the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
Estensione del metodo Object. ToStringExtending the Object.ToString method
Poiché un tipo eredita il metodo Object.ToString predefinito, è possibile che il comportamento sia indesiderato e che si desideri modificarlo.Because a type inherits the default Object.ToString method, you may find its behavior undesirable and want to change it. Questa operazione è particolarmente valida per le matrici e le classi di raccolta.This is particularly true of arrays and collection classes. Sebbene sia possibile prevedere che il metodo ToString
di una matrice o di una classe di raccolta visualizzi i valori dei relativi membri, viene invece visualizzato il tipo nome completo del tipo, come illustrato nell'esempio seguente.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]
Sono disponibili diverse opzioni per produrre la stringa di risultato desiderata.You have several options to produce the result string that you'd like.
Se il tipo è una matrice, un oggetto raccolta o un oggetto che implementa le interfacce IEnumerable o IEnumerable<T>, è possibile enumerarne gli elementi usando l'istruzione
foreach
in C# o il costruttoFor Each...Next
in Visual Basic.If the type is an array, a collection object, or an object that implements the IEnumerable or IEnumerable<T> interfaces, you can enumerate its elements by using theforeach
statement in C# or theFor Each...Next
construct in Visual Basic.Se la classe non è
sealed
(in C#) oNotInheritable
(in Visual Basic), è possibile sviluppare una classe wrapper che eredita dalla classe di base di cui si desidera personalizzare il metodo Object.ToString.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. Come minimo, è necessario eseguire le operazioni seguenti:At a minimum, this requires that you do the following:Implementare tutti i costruttori necessari.Implement any necessary constructors. Le classi derivate non ereditano i relativi costruttori della classe base.Derived classes do not inherit their base class constructors.
Eseguire l'override del metodo Object.ToString per restituire la stringa di risultato desiderata.Override the Object.ToString method to return the result string that you'd like.
Nell'esempio seguente viene definita una classe wrapper per la classe List<T>.The following example defines a wrapper class for the List<T> class. Esegue l'override del metodo Object.ToString per visualizzare il valore di ogni metodo della raccolta anziché il nome completo del tipo.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
Sviluppare un metodo di estensione che restituisca la stringa di risultato desiderata.Develop an extension method that returns the result string that you want. Si noti che non è possibile eseguire l'override del metodo di Object.ToString predefinito in questo modo (ovvero la classe C#di estensione (in) o il modulo (in Visual Basic) non può avere un metodo senza parametri denominato
ToString
che viene chiamato al posto del metodoToString
del tipo originale.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. È necessario specificare un altro nome per la sostituzione senza parametriToString
.You'll have to provide some other name for your parameterlessToString
replacement.Nell'esempio seguente vengono definiti due metodi che estendono la classe List<T>: un metodo
ToString2
senza parametri e un metodoToString
con un parametro String che rappresenta una stringa di 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 }
Note per il Windows RuntimeWindows RuntimeNotes for the Windows RuntimeWindows Runtime
Quando si chiama il metodo ToString su una classe nell'Windows RuntimeWindows Runtime, fornisce il comportamento predefinito per le classi che non eseguono l'override 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. Questo è parte del supporto fornito dal .NET Framework per la Windows RuntimeWindows Runtime (vedere .NET Framework supporto per le app di Windows Store e Windows Runtime).This is part of the support that the .NET Framework provides for the Windows RuntimeWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Le classi nella Windows RuntimeWindows Runtime non ereditano Objecte non sempre implementano un ToString.Classes in the Windows RuntimeWindows Runtime don't inherit Object, and don't always implement a ToString. Tuttavia, presentano sempre i metodi ToString, Equals(Object)e GetHashCode quando vengono usati nel codice C# o Visual Basic e il .NET Framework fornisce un comportamento predefinito per questi metodi.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 partire dalla .NET Framework 4.5.1.NET Framework 4.5.1, il Common Language Runtime utilizzerà l'oggetto di . ToString in un oggetto Windows RuntimeWindows Runtime prima di eseguire il fallback all'implementazione predefinita di Object.ToString.Starting with the .NET Framework 4.5.1.NET Framework 4.5.1, the common language runtime will use IStringable.ToString on a Windows RuntimeWindows Runtime object before falling back to the default implementation of Object.ToString.
Nota
Windows RuntimeWindows Runtime classi scritte in C# o Visual Basic possono eseguire l'override del metodo ToString.classes that are written in C# or Visual Basic can override the ToString method.
Il Windows RuntimeWindows Runtime e l'interfaccia di cui è stato ritringThe Windows RuntimeWindows Runtime and the IStringable Interface
A partire da Windows 8,1Windows 8.1, il Windows RuntimeWindows Runtime include un'interfaccia di cui il singolo metodo, dicui è possibile eseguire la formattazione , fornisce un supporto di formattazione di base analogo a quello fornito da 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. Per evitare ambiguità, è consigliabile non implementare l'applicazione dell' applicazione per i tipi gestiti.To prevent ambiguity, you should not implement IStringable on managed types.
Quando gli oggetti gestiti vengono chiamati da codice nativo o da codice scritto in linguaggi come JavaScript o C++/CX, sembrano implementare l'oggetto di tipo.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. Il Common Language Runtime instraderà automaticamente le chiamate da untringable. ToString a Object.ToString nell'evento che è possibile implementare nell'oggetto gestito.The common language runtime will automatically route calls from IStringable.ToString to Object.ToString in the event IStringable is not implemented on the managed object.
Avviso
Poiché il Common Language Runtime implementa automaticamente l'oggetto per tutti i tipi gestiti nelle app Windows StoreWindows Store, si consiglia di non fornire un'implementazione di di proprietà .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. L' implementazione di /CX può comportare un comportamento imprevisto quando si chiama ToString
da C++Windows RuntimeWindows Runtime, o JavaScript.Implementing IStringable may result in unintended behavior when calling ToString
from the Windows RuntimeWindows Runtime, C++/CX, or JavaScript.
Se si sceglie di implementare la pagina relativa all' implementazione di in un tipo gestito pubblico esportato in un componente Windows RuntimeWindows Runtime, si applicano le restrizioni seguenti:If you do choose to implement IStringable in a public managed type that is exported in a Windows RuntimeWindows Runtime component, the following restrictions apply:
È possibile definire l'interfaccia che può essere considerata solo in una relazione di tipo "classe Implements", ad esempioYou can define the IStringable interface only in a "class implements" relationship, such as
public class NewClass : IStringable
in C# oppurein C#, or
Public Class NewClass : Implements IStringable
in Visual Basic.in Visual Basic.
Non è possibile implementare l' oggetto che è possibile implementare in un'interfaccia.You cannot implement IStringable on an interface.
Non è possibile dichiarare un parametro di tipo.You cannot declare a parameter to be of type IStringable.
L' oggetto non può essere il tipo restituito di un metodo, di una proprietà o di un campo.IStringable cannot be the return type of a method, property, or field.
Non è possibile nascondere l'implementazione di che può essere considerata dalle classi di base usando una definizione di metodo simile alla seguente: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"; } }
Al contrario, l'implementazione di . ToString è sempre necessario eseguire l'override dell'implementazione della classe di base.Instead, the IStringable.ToString implementation must always override the base class implementation. Puoi nascondere un'implementazione di
ToString
solo richiamandola sull'istanza di una classe fortemente tipizzata.You can hide aToString
implementation only by invoking it on a strongly typed class instance.
Si noti che in un'ampia gamma di condizioni, le chiamate dal codice nativo a un tipo gestito che implementa l' oggetto o che nasconde l'implementazione di ToString possono produrre un comportamento imprevisto.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.
Note per gli eredi
Quando si implementano tipi personalizzati, è necessario eseguire l'override del metodo ToString() per restituire valori significativi per tali tipi.When you implement your own types, you should override the ToString() method to return values that are meaningful for those types. Le classi derivate che richiedono un maggiore controllo sulla formattazione rispetto a ToString() fornisce possono implementare l'interfaccia IFormattable.Derived classes that require more control over formatting than ToString() provides can implement the IFormattable interface. Il ToString(String, IFormatProvider) metodo consente di definire stringhe di formato che controllano la formattazione e di usare un oggetto IFormatProvider che può fornire la formattazione specifica delle impostazioni cultura.Its ToString(String, IFormatProvider) method enables you to define format strings that control formatting and to use an IFormatProvider object that can provide for culture-specific formatting.
Le sostituzioni del metodo ToString() devono rispettare le linee guida seguenti:Overrides of the ToString() method should follow these guidelines: -La stringa restituita deve essere intuitiva e leggibile dagli utenti.- The returned string should be friendly and readable by humans.
-La stringa restituita deve identificare in modo univoco il valore dell'istanza dell'oggetto.- The returned string should uniquely identify the value of the object instance.
-La stringa restituita deve essere il più breve possibile, in modo che sia adatta per la visualizzazione da parte di un debugger.- The returned string should be as short as possible so that it is suitable for display by a debugger.
-L'override del ToString() non deve restituire Empty o una stringa null.- Your ToString() override should not return Empty or a null string.
-L'override del ToString() non deve generare un'eccezione.- Your ToString() override should not throw an exception.
-Se la rappresentazione di stringa di un'istanza è dipendente dalle impostazioni cultura o può essere formattata in diversi modi, implementare l'interfaccia IFormattable.- If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the IFormattable interface.
-Se la stringa restituita include informazioni riservate, è necessario innanzitutto richiedere un'autorizzazione appropriata.- If the returned string includes sensitive information, you should first demand an appropriate permission. Se la richiesta ha esito positivo, è possibile restituire le informazioni riservate. in caso contrario, è necessario restituire una stringa che escluda le informazioni riservate.If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.
-L'override del ToString() non deve avere effetti collaterali osservabili per evitare complicazioni durante il debug.- Your ToString() override should have no observable side effects to avoid complications in debugging. Una chiamata al metodo ToString(), ad esempio, non deve modificare il valore dei campi di istanza.For example, a call to the ToString() method should not change the value of instance fields.
-Se il tipo implementa un metodo di analisi (o Parse
o TryParse
metodo, un costruttore o un altro metodo statico che crea un'istanza del tipo da una stringa), è necessario assicurarsi che la stringa restituita dal metodo ToString() possa essere convertita in un istanza dell'oggetto.- 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.