Metodo System.Object.ToString

Questo articolo fornisce osservazioni supplementari alla documentazione di riferimento per questa API.

Object.ToString è un metodo di formattazione comune in .NET. Converte un oggetto nella relativa rappresentazione di stringa in modo che sia adatto per la visualizzazione. Per informazioni sul supporto della formattazione in .NET, vedere Formattazione dei tipi. Le implementazioni predefinite del Object.ToString metodo restituiscono il nome completo del tipo dell'oggetto.

Importante

È possibile che sia stata raggiunta questa pagina seguendo il collegamento dall'elenco dei membri di un altro tipo. Ciò è dovuto al fatto che tale tipo non esegue l'override Object.ToStringdi . Eredita invece la funzionalità del Object.ToString metodo .

I tipi eseguono spesso l'override del Object.ToString metodo per fornire una rappresentazione di stringa più appropriata di un particolare tipo. I tipi eseguono spesso anche l'overload del Object.ToString metodo per fornire supporto per le stringhe di formato o la formattazione sensibile alle impostazioni cultura.

Metodo Object.ToString() predefinito

L'implementazione predefinita del ToString metodo restituisce il nome completo del tipo di Object, come illustrato nell'esempio seguente.

Object obj = new Object();
Console.WriteLine(obj.ToString());

// The example displays the following output:
//      System.Object
let obj = obj ()
printfn $"{obj.ToString()}"
// printfn $"{obj}" // Equivalent

// The example displays the following output:
//      System.Object
Module Example3
    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 riferimento in .NET, questo comportamento viene ereditato dai tipi di riferimento che non eseguono l'override del ToString metodo. Ciò è illustrato nell'esempio seguente. Definisce una classe denominata Object1 che accetta l'implementazione predefinita di tutti i Object membri. Il ToString metodo restituisce il nome completo del tipo dell'oggetto.

using System;
using Examples;

namespace Examples
{
   public class Object1
   {
   }
}

public class Example5
{
   public static void Main()
   {
      object obj1 = new Object1();
      Console.WriteLine(obj1.ToString());
   }
}
// The example displays the following output:
//   Examples.Object1
type Object1() = class end

let obj1 = Object1()
printfn $"{obj1.ToString()}"
// The example displays the following output:
//   Examples.Object1
Public Class Object1
End Class

Module Example4
    Public Sub Main()
        Dim obj1 As New Object1()
        Console.WriteLine(obj1.ToString())
    End Sub
End Module
' The example displays the following output:
'   Examples.Object1

Eseguire l'override del metodo Object.ToString()

I tipi in genere eseguono l'override del Object.ToString metodo per restituire una stringa che rappresenta l'istanza dell'oggetto. Ad esempio, i tipi di base, Charad esempio , Int32e String forniscono ToString implementazioni che restituiscono il formato stringa del valore rappresentato dall'oggetto. Nell'esempio seguente viene definita una classe , Object2, che esegue l'override del ToString metodo per restituire il nome del tipo insieme al relativo valore.

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 Example6
{
   public static void Main()
   {
      Object2 obj2 = new Object2('a');
      Console.WriteLine(obj2.ToString());
   }
}
// The example displays the following output:
//       Object2: a
type Object2(value: obj) =
    inherit obj ()
    override _.ToString() =
        base.ToString() + ": " + value.ToString()

let obj2 = Object2 'a'
printfn $"{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 Example5
    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 indica se eseguono o meno l'override del Object.ToString metodo.

Categoria di tipi Esegue l'override di Object.ToString() Comportamento
Classe n/d n/d
Struttura Sì (ValueType.ToString) Uguale a Object.ToString()
Enumerazione Sì (Enum.ToString()) Nome del membro
Interfaccia No n/d
Delega No n/d

Per altre informazioni sull'override di , vedere la sezione Notes to Inheritors .See the Notes to Inheritors section for additional information on overriding ToString.

Overload del metodo ToString

Oltre a eseguire l'override del metodo senza Object.ToString() parametri, molti tipi eseguono l'overload del ToString metodo per fornire versioni del metodo che accettano parametri. In genere, questa operazione viene eseguita per fornire supporto per la formattazione delle variabili e la formattazione sensibile alle impostazioni cultura.

Nell'esempio seguente viene sottoposto a overload del ToString metodo per restituire una stringa di risultato che include il valore di vari campi di una Automobile classe. 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 A, che restituisce una stringa con tutti e quattro i valori di campo.

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 Example7
{
   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
open System

type Automobile(model: string, year: int, doors: int, cylinders: string) =
    member _.Doors = doors
    member _.Model = model
    member _.Year = year
    member _.Cylinders = cylinders

    override this.ToString() =
        this.ToString "G"

    member _.ToString(fmt) =
        let fmt = 
            if String.IsNullOrEmpty fmt then "G"
            else fmt.ToUpperInvariant()

        match fmt with
        | "G" ->
            $"{year} {model}"
        | "D" ->
            $"{year} {model}, {doors} dr."
        | "C" ->
            $"{year} {model}, {cylinders}"
        | "A" ->
            $"{year} {model}, {doors} dr. {cylinders}"
        | _ ->
            raise (ArgumentException $"'{fmt}' is an invalid format string")

let auto = Automobile("Lynx", 2016, 4, "V8")
printfn $"{auto}"
printfn $"""{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 Example6
    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 overload Decimal.ToString(String, IFormatProvider) per visualizzare la formattazione sensibile alle impostazioni cultura di un valore di valuta.

using System;
using System.Globalization;

public class Example8
{
   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
open System.Globalization

let cultureNames =
    [| "en-US"; "en-GB"; "fr-FR"; "hr-HR"; "ja-JP" |]
let value = 1603.49m
for cultureName in cultureNames do
    let culture = CultureInfo cultureName
    printfn $"""{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 Example7
    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 altre informazioni sulle stringhe di formato e sulla formattazione sensibile alle impostazioni cultura, vedere Formattazione dei tipi. Per le stringhe di formato supportate dai valori numerici, vedere Stringhe di formato numerico standard e Stringhe di formato numerico personalizzato. Per le stringhe di formato supportate dai valori di data e ora, vedere Stringhe di formato data e ora standard e stringhe di formato di data e ora personalizzate.

Estendere il metodo Object.ToString

Poiché un tipo eredita il metodo predefinito Object.ToString , potrebbe verificarne il comportamento indesiderato e modificarlo. Ciò è particolarmente vero per le matrici e le classi di raccolta. Anche se è possibile che il ToString metodo di una matrice o di una classe di raccolta visualizzi i valori dei relativi membri, visualizza invece il nome completo del tipo, come illustrato nell'esempio seguente.

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]
let values = [| 1; 2; 4; 8; 16; 32; 64; 128 |]
printfn $"{values}"

let list = ResizeArray values
printfn $"{list}"

// 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.

  • Se il tipo è una matrice, un oggetto raccolta o un oggetto che implementa le interfacce o IEnumerable<T> , è possibile enumerare i IEnumerable relativi elementi usando l'istruzione foreach in C# o il For Each...Next costrutto in Visual Basic.

  • Se la classe non sealed è (in C#) o NotInheritable (in Visual Basic), è possibile sviluppare una classe wrapper che eredita dalla classe base il cui Object.ToString metodo si vuole personalizzare. Come minimo, è necessario eseguire le operazioni seguenti:

    1. Implementare tutti i costruttori necessari. Le classi derivate non ereditano i costruttori della classe di base.
    2. Eseguire l'override del Object.ToString metodo per restituire la stringa di risultato desiderata.

    Nell'esempio seguente viene definita una classe wrapper per la List<T> classe . Esegue l'override del Object.ToString metodo per visualizzare il valore di ogni metodo della raccolta anziché il nome completo del tipo.

    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 Example2
    {
       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
    
    open System
    open System.Collections.Generic
    
    type CList<'T>() = 
        inherit ResizeArray<'T>()
        
        override this.ToString() =
            let mutable retVal = String.Empty
            for item in this do
                if String.IsNullOrEmpty retVal then
                    retVal <- retVal + string item
                else
                    retVal <- retVal + $", {item}"
            retVal
    
    let list2 = CList()
    list2.Add 1000
    list2.Add 2000
    printfn $"{list2}"
    // 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 Example1
        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 restituisce la stringa di risultato desiderata. Si noti che non è possibile eseguire l'override del metodo predefinito Object.ToString in questo modo, ovvero la classe di estensione (in C#) o il modulo (in Visual Basic) non può avere un metodo senza parametri denominato ToString chiamato al posto del metodo del ToString tipo originale. Sarà necessario specificare un altro nome per la sostituzione senza ToString parametri.

    Nell'esempio seguente vengono definiti due metodi che estendono la List<T> classe: un metodo senza ToString2 parametri e un ToString metodo con un String parametro che rappresenta una stringa di formato.

    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 Example3
    {
       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 }
    
    open System
    open System.Collections.Generic
    
    type List<'T> with
        member this.ToString2<'T>() = 
            let mutable retVal = String.Empty
            for item in this do
               retVal <- retVal + $"""{if String.IsNullOrEmpty retVal then "" else ", "}{item}"""
            if String.IsNullOrEmpty retVal then "{}" else "{ " + retVal + " }"
    
        member this.ToString<'T>(fmt: string) =
            let mutable retVal = String.Empty
            for item in this do
                match box item with
                | :? IFormattable as ifmt ->
                    retVal <- retVal + $"""{if String.IsNullOrEmpty retVal then "" else ", "}{ifmt.ToString(fmt, null)}"""
                | _ ->
                    retVal <- retVal + this.ToString2()
            if String.IsNullOrEmpty retVal then "{}" else "{ " + retVal + " }"
    
    let list = ResizeArray()
    list.Add 1000
    list.Add 2000
    printfn $"{list.ToString2()}"
    printfn $"""{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 Example2
        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 Windows Runtime

Quando chiami il ToString metodo su una classe in Windows Runtime, fornisce il comportamento predefinito per le classi che non eseguono l'override ToStringdi . Questo è parte del supporto fornito da .NET per Windows Runtime (vedere Supporto .NET per le app di Windows Store e Windows Runtime). Le classi in Windows Runtime non ereditano Objecte non implementano sempre .ToString Tuttavia, sembrano ToStringavere sempre metodi , Equals(Object)e GetHashCode quando vengono usati nel codice C# o Visual Basic e .NET fornisce un comportamento predefinito per questi metodi.

Common Language Runtime usa IStringable.ToString in un oggetto Windows Runtime prima di eseguire il fallback all'implementazione predefinita di Object.ToString.

Nota

Le classi di Windows Runtime scritte in C# o Visual Basic possono eseguire l'override del ToString metodo .

Windows Runtime e l'interfaccia IStringable

Windows Runtime include un'interfaccia IStringable il cui singolo metodo, IStringable.ToString, fornisce un supporto di formattazione di base paragonabile a quello fornito da Object.ToString. Per evitare ambiguità, non è consigliabile implementare IStringable nei tipi gestiti.

Quando gli oggetti gestiti vengono chiamati dal codice nativo o dal codice scritto in linguaggi come JavaScript o C++/CX, sembrano implementare IStringable. Common Language Runtime instrada automaticamente le chiamate da IStringable.ToString a Object.ToString se IStringable non è implementato nell'oggetto gestito.

Avviso

Poiché Common Language Runtime implementa automaticamente IStringable per tutti i tipi gestiti nelle app di Windows Store, è consigliabile non fornire la propria IStringable implementazione. L'implementazione IStringable può comportare comportamenti imprevisti durante la chiamata ToString da Windows Runtime, C++/CX o JavaScript.

Se si sceglie di implementare IStringable in un tipo gestito pubblico esportato in un componente Windows Runtime, si applicano le restrizioni seguenti:

  • È possibile definire l'interfaccia IStringable solo in una relazione "class implements", come indicato di seguito:

    public class NewClass : IStringable
    
    Public Class NewClass : Implements IStringable
    
  • Non è possibile implementare IStringable in un'interfaccia.

  • Non è possibile dichiarare un parametro di tipo IStringable.

  • IStringable non può essere il tipo restituito di un metodo, di una proprietà o di un campo.

  • Non è possibile nascondere l'implementazione IStringable dalle classi di base usando una definizione del metodo, ad esempio:

    public class NewClass : IStringable
    {
       public new string ToString()
       {
          return "New ToString in NewClass";
       }
    }
    

    L'implementazione di IStringable.ToString deve invece eseguire sempre l'override dell'implementazione della classe di base. Puoi nascondere un'implementazione di ToString solo richiamandola sull'istanza di una classe fortemente tipizzata.

In diverse condizioni, le chiamate dal codice nativo a un tipo gestito che implementa IStringable o nasconde l'implementazione ToString possono produrre un comportamento imprevisto.