System.Object.ToString, metoda

Ten artykuł zawiera dodatkowe uwagi dotyczące dokumentacji referencyjnej dla tego interfejsu API.

Object.ToString to typowa metoda formatowania na platformie .NET. Konwertuje obiekt na jego reprezentację ciągu, aby był odpowiedni do wyświetlania. (Aby uzyskać informacje o obsłudze formatowania na platformie .NET, zobacz Typy formatowania). Domyślne implementacje Object.ToString metody zwracają w pełni kwalifikowaną nazwę typu obiektu.

Ważne

Być może osiągnięto tę stronę, korzystając z linku z listy członków innego typu. Wynika to z faktu, że ten typ nie zastępuje Object.ToStringelementu . Zamiast tego dziedziczy funkcjonalność Object.ToString metody .

Typy często zastępują metodę Object.ToString , aby zapewnić bardziej odpowiednią reprezentację ciągu określonego typu. Typy często przeciążają również metodę Object.ToString , aby zapewnić obsługę ciągów formatu lub formatowania wrażliwego na kulturę.

Domyślna metoda Object.ToString()

Domyślna implementacja ToString metody zwraca w pełni kwalifikowaną nazwę typu Object, jak pokazano w poniższym przykładzie.

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

Ponieważ Object jest klasą bazową wszystkich typów odwołań na platformie .NET, to zachowanie jest dziedziczone przez typy odwołań, które nie zastępują ToString metody. Ilustruje to poniższy przykład. Definiuje klasę o nazwie Object1 , która akceptuje domyślną implementację wszystkich Object elementów członkowskich. Metoda ToString zwraca w pełni kwalifikowaną nazwę typu obiektu.

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

Zastąpij metodę Object.ToString()

Typy często zastępują metodę Object.ToString , aby zwrócić ciąg reprezentujący wystąpienie obiektu. Na przykład typy podstawowe, takie jak Char, Int32i String zapewniają ToString implementacje, które zwracają postać ciągu wartości reprezentowanej przez obiekt. W poniższym przykładzie zdefiniowano klasę , Object2która zastępuje ToString metodę w celu zwrócenia nazwy typu wraz z jej wartością.

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

W poniższej tabeli wymieniono kategorie typów na platformie .NET i wskazuje, czy zastępują one metodę Object.ToString .

Kategoria typów Zastępuje obiekt.ToString() Zachowanie
Klasa nie dotyczy nie dotyczy
Struktura Tak (ValueType.ToString) Tak samo jak Object.ToString()
Wyliczanie Tak (Enum.ToString()) Nazwa elementu członkowskiego
Interfejs Nie. nie dotyczy
Delegat Nie. nie dotyczy

Aby uzyskać dodatkowe informacje na temat zastępowania ToString, zobacz sekcję Uwagi do dziedziczenia.

Przeciążenie metody ToString

Oprócz zastąpienia metody bez Object.ToString() parametrów wiele typów przeciąża ToString metodę, aby udostępnić wersje metody, które akceptują parametry. Najczęściej jest to wykonywane w celu zapewnienia obsługi formatowania zmiennych i formatowania wrażliwego na kulturę.

Poniższy przykład przeciąża metodę ToString , aby zwrócić ciąg wynikowy, który zawiera wartość różnych pól Automobile klasy. Definiuje cztery ciągi formatu: G, które zwracają nazwę modelu i rok; D, która zwraca nazwę modelu, rok i liczbę drzwi; C, który zwraca nazwę modelu, rok i liczbę cylindrów; i A, który zwraca ciąg ze wszystkimi czterema wartościami pól.

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

W poniższym przykładzie wywołana jest przeciążona Decimal.ToString(String, IFormatProvider) metoda w celu wyświetlenia formatowania z uwzględnieniem kultury wartości waluty.

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

Aby uzyskać więcej informacji na temat formatowania ciągów i formatowania wrażliwego na kulturę, zobacz Typy formatowania. Aby zapoznać się z ciągami formatu obsługiwanymi przez wartości liczbowe, zobacz Standardowe ciągi formatu liczbowego i Niestandardowe ciągi formatu liczbowego. Aby zapoznać się z ciągami formatu obsługiwanymi przez wartości daty i godziny, zobacz Standardowe ciągi formatu daty i godziny oraz niestandardowe ciągi formatu daty i godziny.

Rozszerzanie metody Object.ToString

Ponieważ typ dziedziczy metodę domyślną Object.ToString , jego zachowanie może być niepożądane i chcesz go zmienić. Dotyczy to szczególnie tablic i klas kolekcji. Chociaż można oczekiwać ToString , że metoda tablicy lub klasy kolekcji wyświetli wartości jej składowych, zamiast tego wyświetla w pełni kwalifikowaną nazwę typu, jak pokazano w poniższym przykładzie.

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]

Istnieje kilka opcji tworzenia ciągu wynikowego, który chcesz.

  • Jeśli typem jest tablica, obiekt kolekcji lub obiekt, który implementuje IEnumerable interfejsy lub IEnumerable<T> , możesz wyliczyć jego elementy przy użyciu foreach instrukcji w języku C# lub For Each...Next konstrukcji w Visual Basic.

  • Jeśli klasa nie sealed jest (w języku C#) lub NotInheritable (w Visual Basic), możesz opracować klasę otoki dziedziczą z klasy bazowej, której Object.ToString metoda ma zostać dostosowana. Co najmniej wymaga to wykonania następujących czynności:

    1. Zaimplementuj wszelkie niezbędne konstruktory. Klasy pochodne nie dziedziczą swoich konstruktorów klas bazowych.
    2. Zastąpi metodę , Object.ToString aby zwrócić ciąg wynikowy, który chcesz.

    W poniższym przykładzie zdefiniowano klasę otoki dla List<T> klasy . Zastępuje metodę Object.ToString , aby wyświetlić wartość każdej metody kolekcji, a nie w pełni kwalifikowaną nazwę typu.

    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
    
  • Opracuj metodę rozszerzenia zwracającą żądany ciąg wynikowy. Należy pamiętać, że w ten sposób nie można zastąpić metody domyślnej Object.ToString — czyli klasy rozszerzenia (w języku C#) lub module (w Visual Basic) nie może mieć metody bez parametrów o nazwie ToString , która jest wywoływana zamiast metody oryginalnego typu ToString . Musisz podać inną nazwę dla zamiany bez ToString parametrów.

    W poniższym przykładzie zdefiniowano dwie metody rozszerzające List<T> klasę: metodę bez ToString2 parametrów i ToString metodę z parametrem String reprezentującym ciąg formatu.

    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 }
    

Uwagi dotyczące środowisko wykonawcze systemu Windows

Wywołanie ToString metody w klasie w środowisko wykonawcze systemu Windows zapewnia domyślne zachowanie klas, które nie zastępują ToStringklasy . Jest to część obsługi zapewnianej przez platformę .NET dla środowisko wykonawcze systemu Windows (zobacz Obsługa platformy .NET dla aplikacji ze Sklepu Windows i środowisko wykonawcze systemu Windows). Klasy w środowisko wykonawcze systemu Windows nie dziedziczą Objectelementów i nie zawsze implementują element ToString. Jednak zawsze wydają się ToStringmieć metody , Equals(Object)i GetHashCode podczas ich używania w kodzie C# lub Visual Basic, a platforma .NET zapewnia domyślne zachowanie tych metod.

Środowisko uruchomieniowe języka wspólnego używa funkcji IStringable.ToString w obiekcie środowisko wykonawcze systemu Windows przed powrotem do domyślnej implementacji Object.ToStringelementu .

Uwaga

środowisko wykonawcze systemu Windows klasy napisane w języku C# lub Visual Basic mogą zastąpić metodę ToString .

Interfejs środowisko wykonawcze systemu Windows i IStringable

Środowisko wykonawcze systemu Windows zawiera interfejs IStringable, którego pojedyncza metoda IStringable.ToString zapewnia podstawową obsługę formatowania porównywalną z tym dostarczonym przez Object.ToStringprogram . Aby zapobiec niejednoznaczności, nie należy implementować funkcji IStringable w typach zarządzanych.

Gdy obiekty zarządzane są wywoływane przez kod natywny lub kod napisany w językach takich jak JavaScript lub C++/CX, wydają się implementować funkcję IStringable. Środowisko uruchomieniowe języka wspólnego automatycznie kieruje wywołania z elementu IStringable.ToString do Object.ToString elementu IStringable, jeśli element IStringable nie jest implementowany w obiekcie zarządzanym.

Ostrzeżenie

Ponieważ środowisko uruchomieniowe języka wspólnego automatycznie implementuje funkcję IStringable dla wszystkich typów zarządzanych w aplikacjach ze Sklepu Windows, zalecamy, aby nie udostępniać własnej IStringable implementacji. Implementacja IStringable może spowodować niezamierzone zachowanie podczas wywoływania ToString z środowisko wykonawcze systemu Windows, C++/CX lub JavaScript.

Jeśli zdecydujesz się zaimplementować funkcję IStringable w publicznym typie zarządzanym wyeksportowanym w składniku środowisko wykonawcze systemu Windows, obowiązują następujące ograniczenia:

  • Interfejs IStringable można zdefiniować tylko w relacji "klasa implementuje" w następujący sposób:

    public class NewClass : IStringable
    
    Public Class NewClass : Implements IStringable
    
  • Nie można zaimplementować funkcji IStringable w interfejsie.

  • Nie można zadeklarować parametru typu IStringable.

  • IStringable nie może być zwracanym typem metody, właściwości lub pola.

  • Nie można ukryć implementacji IStringable z klas bazowych przy użyciu definicji metody, takiej jak:

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

    Zamiast tego implementacja IStringable.ToString musi zawsze zastąpić implementację klasy bazowej. Implementację ToString można ukryć tylko przez wywołanie jej w silnie typiowanym wystąpieniu klasy.

W różnych warunkach wywołania z kodu natywnego do typu zarządzanego, który implementuje funkcję IStringable lub ukrywa implementację ToString , mogą powodować nieoczekiwane zachowanie.