Object.ToString Object.ToString Object.ToString Object.ToString Method

定義

傳回代表目前物件的字串。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

傳回

表示目前物件的字串。A string that represents the current object.

備註

Object.ToString是 .NET Framework 中的主要格式化方法。Object.ToString is the major formatting method in the .NET Framework. 它會將物件轉換成其字串表示,使其適合顯示。It converts an object to its string representation so that it is suitable for display. (如需 .NET Framework 中格式支援的相關資訊,請參閱格式化類型。)Object.ToString方法的預設執行會傳回物件類型的完整名稱。(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.

重要

您可能會遵循另一個類型成員清單中的連結,來到達此頁面。You may have reached this page by following the link from the member list of another type. 這是因為該類型不會覆Object.ToString寫。That is because that type does not override Object.ToString. 相反地,它會繼承Object.ToString方法的功能。Instead, it inherits the functionality of the Object.ToString method.

類型經常會覆Object.ToString寫方法,以提供更適合特定類型的字串標記法。Types frequently override the Object.ToString method to provide a more suitable string representation of a particular type. 類型也經常Object.ToString會多載方法,以提供格式字串或區分文化特性格式的支援。Types also frequently overload the Object.ToString method to provide support for format strings or culture-sensitive formatting.

本節內容:In this section:

預設的物件 ToString ()方法 The default Object.ToString() method
覆寫物件 ToString ()方法 Overriding the Object.ToString() method
多載 ToString 方法 Overloading the ToString method
擴充物件. ToString 方法 Extending the Object.ToString method
Windows 執行階段的注意事項Notes for the Windows Runtime

預設的物件 ToString ()方法The default Object.ToString() method

ToString方法的預設執行會傳回類型Object的完整名稱,如下列範例所示。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

因為Object是 .NET Framework 中所有參考型別的基類,所以不會覆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. 下列範例將說明這點。The following example illustrates this. 它會定義名為Object1的類別,接受所有Object成員的預設執行。It defines a class named Object1 that accepts the default implementation of all Object members. ToString方法會傳回物件的完整型別名稱。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

覆寫物件 ToString ()方法Overriding the Object.ToString() method

類型通常會覆Object.ToString寫方法,以傳回代表物件實例的字串。Types commonly override the Object.ToString method to return a string that represents the object instance. 例如, Char ToStringInt32String等基底類型提供的實作為傳回物件所代表之值的字串形式。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. 下列範例會定義一個類別, Object2它會ToString覆寫方法以傳回型別名稱及其值。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

下表列出 .net 中的類型類別目錄,並指出它們是否覆寫Object.ToString方法。The following table lists the type categories in .NET and indicates whether or not they override the Object.ToString method.

型別分類Type category 覆寫物件 ToString ()Overrides Object.ToString() 行為Behavior
類別Class N/An/a N/An/a
結構Structure 是(ValueType.ToStringYes (ValueType.ToString) Object.ToString() 相同Same as Object.ToString()
列舉Enumeration 是(Enum.ToString()Yes (Enum.ToString()) 成員名稱The member name
介面Interface No N/An/a
Delegate - 委派Delegate No N/An/a

如需覆寫ToString的其他資訊,請參閱「繼承者注意事項」一節。See the Notes to Inheritors section for additional information on overriding ToString.

多載 ToString 方法Overloading the ToString method

除了覆寫無參數Object.ToString()方法以外,許多型別會多ToString載方法,以提供接受參數之方法的版本。In addition to overriding the parameterless Object.ToString() method, many types overload the ToString method to provide versions of the method that accept parameters. 最常見的做法是為了支援可變格式和區分文化特性的格式。Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting.

下列範例ToString會多載方法,以傳回結果字串,其中包含Automobile類別之各種欄位的值。The following example overloads the ToString method to return a result string that includes the value of various fields of an Automobile class. 它會定義四個格式字串:G,傳回模型名稱和年份;D,會傳回模型名稱、年份和門的數目;C,會傳回模型名稱、年份和圓柱的數目;和,它會傳回包含全部四個域值的字串。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

下列範例會呼叫多載Decimal.ToString(String, IFormatProvider)的方法,以顯示貨幣值的區分文化特性格式。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

如需有關格式字串和區分文化特性格式的詳細資訊,請參閱格式化類型For more information on format strings and culture-sensitive formatting, see Formatting Types. 如需數值所支援的格式字串,請參閱標準數值格式字串自訂數值格式字串For the format strings supported by numeric values, see Standard Numeric Format Strings and Custom Numeric Format Strings. 如需日期和時間值所支援的格式字串,請參閱標準日期和時間格式字串自訂日期和時間格式字串For the format strings supported by date and time values, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

擴充物件. ToString 方法Extending the Object.ToString method

因為型別會繼承預設Object.ToString的方法,所以您可能會發現不想要的行為,而且要加以變更。Because a type inherits the default Object.ToString method, you may find its behavior undesirable and want to change it. 這特別適用于陣列和集合類別。This is particularly true of arrays and collection classes. 雖然您可能會預期ToString陣列或集合類別的方法顯示其成員的值,但它會改為顯示類型的完整類型名稱,如下列範例所示。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]

您有數個選項可以產生您想要的結果字串。You have several options to produce the result string that you'd like.

  • 如果類型是陣列、集合物件或執行IEnumerableIEnumerable<T>介面的物件,您可以使用中foreach C#的語句或 Visual Basic 中的For Each...Next結構,來列舉其元素。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 the foreach statement in C# or the For Each...Next construct in Visual Basic.

  • 如果sealed類別不是(在中C#)或NotInheritable (在 Visual Basic 中),您可以開發繼承自基類Object.ToString的包裝函式類別,該類別的方法是您想要自訂的。If the class is not sealed (in C#) or NotInheritable (in Visual Basic), you can develop a wrapper class that inherits from the base class whose Object.ToString method you want to customize. 您至少需要執行下列動作:At a minimum, this requires that you do the following:

    1. 執行任何必要的函數。Implement any necessary constructors. 衍生類別不會繼承其基類的函式。Derived classes do not inherit their base class constructors.

    2. 覆寫Object.ToString方法以傳回您想要的結果字串。Override the Object.ToString method to return the result string that you'd like.

    下列範例會定義List<T>類別的包裝函式類別。The following example defines a wrapper class for the List<T> class. 它會覆Object.ToString寫方法,以顯示集合中每個方法的值,而不是完整的類型名稱。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
    
  • 開發擴充方法,以傳回您想要的結果字串。Develop an extension method that returns the result string that you want. 請注意,您無法以這Object.ToString種方式覆寫預設方法(也就是您的擴充C#類別(在中)或模組(在 Visual Basic 中)不ToString能有名為的無參數方法,其會呼叫來取代原始類型的ToString方法。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 named ToString that is called in place of the original type's ToString method. 您必須為無參數ToString的取代提供其他名稱。You'll have to provide some other name for your parameterless ToString replacement.

    下列範例會List<T>定義兩個擴充類別的方法:無參數ToString2方法, String以及ToString具有代表格式字串之參數的方法。The following example defines two methods that extend the List<T> class: a parameterless ToString2 method, and a ToString 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 }
    

的附注Windows 執行階段Windows RuntimeNotes for the Windows 執行階段Windows Runtime

當您在的ToString Windows 執行階段Windows Runtime類別上呼叫方法時,它會為不會覆寫ToString的類別提供預設行為。When you call the ToString method on a class in the Windows 執行階段Windows Runtime, it provides the default behavior for classes that don't override ToString. 這是 .NET Framework 為提供Windows 執行階段Windows Runtime的支援之一部分(請參閱Windows Store 應用程式的 .NET Framework 支援和 Windows 執行階段)。This is part of the support that the .NET Framework provides for the Windows 執行階段Windows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). 中的Windows 執行階段Windows Runtime類別不會Object繼承, ToString而且不一定會執行。Classes in the Windows 執行階段Windows Runtime don't inherit Object, and don't always implement a ToString. 不過,當您在或 Visual Basic ToString程式Equals(Object) C#代碼中GetHashCode使用這些方法時,它們一律會出現、和方法,而 .NET Framework 則會提供這些方法的預設行為。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.

從開始Windows 執行階段Windows Runtime Object.ToString,通用語言執行平臺會在物件上使用 IStringable,然後回到的預設執行。 .NET Framework 4.5.1.NET Framework 4.5.1Starting with the .NET Framework 4.5.1.NET Framework 4.5.1, the common language runtime will use IStringable.ToString on a Windows 執行階段Windows Runtime object before falling back to the default implementation of Object.ToString.

注意

Windows 執行階段Windows Runtime在或 Visual Basic 中C#撰寫的ToString類別可以覆寫方法。classes that are written in C# or Visual Basic can override the ToString method.

Windows 執行階段Windows Runtime和 IStringable 介面The Windows 執行階段Windows Runtime and the IStringable Interface

Object.ToString從開始Windows 8.1Windows 8.1 Windows 執行階段Windows Runtime ,會包含 IStringable 介面,其單一方法 IStringable 會提供與所提供的基本格式支援。Starting with Windows 8.1Windows 8.1, the Windows 執行階段Windows Runtime includes an IStringable interface whose single method, IStringable.ToString, provides basic formatting support comparable to that provided by Object.ToString. 為避免不明確,您不應該在 managed 類型上執行IStringableTo prevent ambiguity, you should not implement IStringable on managed types.

當原生程式碼或以 JavaScript 或C++/cx 等語言撰寫的程式碼呼叫 managed 物件時,它們似乎會執行IStringableWhen managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement IStringable. 當事件IStringable未在 managed 物件上執行時,common language Object.ToString runtime 會自動將來自 IStringable 的呼叫路由傳送至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.

警告

由於 common language runtime 會針對應用程式Windows 市集Windows Store的所有 managed 類型自動執行 IStringable,因此建議您不要提供自己的IStringableBecause the common language runtime auto-implements IStringable for all managed types in Windows 市集Windows Store apps, we recommend that you do not provide your own IStringable implementation. ToStringWindows 執行階段Windows Runtime/cx 或 JavaScript 呼叫時, C++執行 IStringable 可能會導致非預期的行為。Implementing IStringable may result in unintended behavior when calling ToString from the Windows 執行階段Windows Runtime, C++/CX, or JavaScript.

如果您選擇在Windows 執行階段Windows Runtime元件中匯出的公用 managed 類型中執行IStringable ,則適用下列限制:If you do choose to implement IStringable in a public managed type that is exported in a Windows 執行階段Windows Runtime component, the following restrictions apply:

  • 您只能在「類別實行」關聯性中定義IStringable介面,例如You can define the IStringable interface only in a "class implements" relationship, such as

    public class NewClass : IStringable  
    

    在 C# 中,或in C#, or

    Public Class NewClass : Implements IStringable  
    

    在 Visual Basic 中。in Visual Basic.

  • 您無法在介面上執行IStringableYou cannot implement IStringable on an interface.

  • 您不能將參數宣告為IStringable類型。You cannot declare a parameter to be of type IStringable.

  • IStringable不可以是方法、屬性或欄位的傳回型別。IStringable cannot be the return type of a method, property, or field.

  • 您不能使用如下所示的方法定義,從基類隱藏IStringable的執行: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";  
       }  
    }  
    
    

    取而代之的是, IStringable必須一律覆寫基類的實作為。Instead, the IStringable.ToString implementation must always override the base class implementation. 您只能藉由針對強型別類別執行個體叫用 ToString 實作來隱藏該實作。You can hide a ToString implementation only by invoking it on a strongly typed class instance.

請注意,在各種情況下,從機器碼呼叫至執行IStringable或隱藏其ToString執行的 managed 類型可能會產生非預期的行為。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.

給繼承者的注意事項

當您執行自己的類型時,您應該覆ToString()寫方法,以傳回對那些類型有意義的值。When you implement your own types, you should override the ToString() method to return values that are meaningful for those types. 需要比ToString()提供更多控制權的衍生類別可以IFormattable執行介面。Derived classes that require more control over formatting than ToString() provides can implement the IFormattable interface. ToString(String, IFormatProvider)的方法可讓您定義格式字串來控制格式,以及IFormatProvider使用可提供給特定文化特性格式的物件。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.

ToString()方法的覆寫應遵循下列指導方針:Overrides of the ToString() method should follow these guidelines: -傳回的字串應該是易記的,而且人類可以閱讀。- The returned string should be friendly and readable by humans.

-傳回的字串應該唯一識別物件實例的值。- The returned string should uniquely identify the value of the object instance.

-傳回的字串應該越短越好,讓偵錯工具可以顯示。- The returned string should be as short as possible so that it is suitable for display by a debugger.

-您ToString()的覆寫Empty不應傳回或 null 字串。- Your ToString() override should not return Empty or a null string.

-您ToString()的覆寫不應該擲回例外狀況。- Your ToString() override should not throw an exception.

-如果實例的字串表示區分文化特性,或可以多種方式進行格式化,請執行IFormattable介面。- If the string representation of an instance is culture-sensitive or can be formatted in multiple ways, implement the IFormattable interface.

-如果傳回的字串包含機密資訊,您應該先要求適當的許可權。- If the returned string includes sensitive information, you should first demand an appropriate permission. 如果要求成功,您可以傳回敏感性資訊;否則,您應該傳回排除機密資訊的字串。If the demand succeeds, you can return the sensitive information; otherwise, you should return a string that excludes the sensitive information.

-您ToString()的覆寫應該沒有可觀察的副作用,以避免發生複雜的偵錯工具。- Your ToString() override should have no observable side effects to avoid complications in debugging. 例如,呼叫ToString()方法時,不應該變更實例欄位的值。For example, a call to the ToString() method should not change the value of instance fields.

-如果您的型別會實作為剖析Parse方法TryParse (或或方法、函式,或從字串具現化型別實例的其他靜態方法),您應該確定ToString()方法所傳回的字串可以是轉換成物件實例。- 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.

適用於

另請參閱