Object.ToString Metodo

Definizione

Restituisce una stringa che rappresenta l'oggetto corrente.

public:
 virtual System::String ^ ToString();
public virtual string ToString ();
public virtual string? ToString ();
abstract member ToString : unit -> string
override this.ToString : unit -> string
Public Overridable Function ToString () As String

Restituisce

String

Stringa che rappresenta l'oggetto corrente.

Commenti

Object.ToStringè il metodo di formattazione principale nel .NET Framework. Converte un oggetto nella relativa rappresentazione di stringa in modo che sia adatto per la visualizzazione. Per informazioni sul supporto della formattazione nella .NET Framework, 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 di Object.ToString. 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.

Contenuto della sezione:

Metodo Object.ToString() predefinito
Override del metodo Object.ToString()
Overload del metodo ToString
Estensione del metodo Object.ToString
Note per il Windows Runtime

Metodo Object.ToString() predefinito

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

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
let obj = obj ()
printfn $"{obj.ToString()}"
// printfn $"{obj}" // Equivalent

// 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 riferimento nella .NET Framework, questo comportamento viene ereditato dai tipi di riferimento che non eseguono l'override del ToString metodo. Questa condizione è illustrata nell'esempio seguente. Definisce una classe denominata Object1 che accetta l'implementazione predefinita di tutti i Object membri. Il metodo ToString restituisce il nome completo del tipo dell'oggetto.

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
type Object1() = class end

let obj1 = Object1()
printfn $"{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()

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 come Char, 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 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
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 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

La tabella seguente elenca 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
Delegato 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 dei campi.

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
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 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) overload per visualizzare la formattazione sensibile alle impostazioni cultura di un valore di valuta.

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

Estensione del metodo Object.ToString

Poiché un tipo eredita il metodo predefinito Object.ToString , potrebbe verificarsi un comportamento indesiderato e modificarlo. Ciò è particolarmente vero per le matrici e le classi di raccolta. Anche se si prevede 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 IEnumerable interfacce o IEnumerable<T> , è possibile enumerare i 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 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 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
    
    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 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. 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 che ToString viene chiamato al posto del metodo del ToString tipo originale. Sarà necessario specificare un altro nome per la sostituzione senza ToString parametri.

    L'esempio seguente definisce due metodi che estendono la List<T> classe: un metodo senza ToString2 parametri e un metodo con un String ToString 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 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 }
    
    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 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 Runtime

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

A partire da .NET Framework 4.5.1, Common Language Runtime usa IStringable.ToString in un oggetto Windows Runtime prima di eseguire il fallback all'implementazione predefinita di Object.ToString.

Nota

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

Interfaccia Windows Runtime e IStringable

A partire da Windows 8.1, il Windows Runtime include un'interfaccia IStringable il cui singolo metodo, IStringable.ToString, fornisce 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 un comportamento imprevisto durante la chiamata ToString dal 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 "classe implementa", 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 di 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.

Si noti che 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.

Note per gli eredi

Quando si implementano tipi personalizzati, è necessario eseguire l'override del ToString() metodo per restituire valori significativi per tali tipi. Le classi derivate che richiedono un maggiore controllo sulla formattazione rispetto ToString() a quanto fornito possono implementare l'interfaccia IFormattable . Il metodo ToString(String, IFormatProvider) consente di definire stringhe di formato che controllano la formattazione e di usare un IFormatProvider oggetto che può fornire per la formattazione specifica delle impostazioni cultura.

Le sostituzioni del ToString() metodo devono seguire queste linee guida:

  • La stringa restituita deve essere descrittiva e leggibile dagli esseri umani.

  • La stringa restituita deve identificare in modo univoco il valore dell'istanza dell'oggetto.

  • La stringa restituita deve essere il più breve possibile in modo che sia adatta per la visualizzazione da parte di un debugger.

  • L'override ToString() non deve restituire Empty o una stringa Null.

  • L'override ToString() non deve generare un'eccezione.

  • Se la rappresentazione di stringa di un'istanza è sensibile alle impostazioni cultura o può essere formattata in diversi modi, implementare l'interfaccia IFormattable .

  • Se la stringa restituita include informazioni riservate, è necessario prima richiedere un'autorizzazione appropriata. Se la domanda ha esito positivo, è possibile restituire le informazioni riservate; in caso contrario, è necessario restituire una stringa che esclude le informazioni riservate.

  • L'override ToString() non deve avere effetti collaterali osservabili per evitare complicazioni nel debug. Ad esempio, una chiamata al ToString() metodo non deve modificare il valore dei campi dell'istanza.

  • Se il tipo implementa un metodo di analisi (o Parse o TryParse , un costruttore o un altro metodo statico che crea un'istanza del tipo da una stringa), è necessario assicurarsi che la stringa restituita dal ToString() metodo possa essere convertita in un'istanza di oggetto.

Si applica a

Vedi anche