Object.ToString 方法

定义

返回一个表示当前对象的 string。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.ToStringThat 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.

备注

本文中的一些 C# 示例在 Try.NET 内联代码运行程序和演练环境中运行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行” 按钮(若有),在交互式窗口中运行示例。When present, select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

本节内容: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. 例如,基类型(如 CharInt32String)提供返回对象所表示的值的字符串形式的 ToString 实现。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/a 不适用n/a
结构Structure 是(ValueType.ToStringYes (ValueType.ToString) Object.ToString() 相同Same as Object.ToString()
枚举Enumeration 是(Enum.ToString()Yes (Enum.ToString()) 成员名称The member name
接口Interface No 不适用n/a
委托Delegate No 不适用n/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> 接口的对象,则可以使用中C#的 foreach 语句或 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 方法(即,扩展类(in 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 Runtime 的说明Notes for the Windows 运行时Windows Runtime

Windows 运行时Windows Runtime中的类调用 ToString 方法时,它将为不重写 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 应用商店应用和 Windows 运行时 .NET Framework 支持)。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,并不总是实现 ToStringClasses in the Windows 运行时Windows Runtime don't inherit Object, and don't always implement a ToString. 但是,当你在C#或 Visual Basic 代码中使用它们时,它们始终具有 ToStringEquals(Object)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.

.NET Framework 4.5.1.NET Framework 4.5.1开始,公共语言运行时将对 Windows 运行时Windows Runtime 对象使用IStringable ,然后再回退到 Object.ToString的默认实现。Starting with the .NET Framework 4.5.1.NET Framework 4.5.1, the common language runtime will use IStringable.ToString on a Windows 运行时Windows Runtime object before falling back to the default implementation of Object.ToString.

备注

用 Visual Basic C#或编写的 Windows 运行时Windows Runtime 类可以重写 ToString 方法。Windows 运行时Windows Runtime 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

Windows 8.1Windows 8.1开始,Windows 运行时Windows Runtime 包括IStringable接口,该接口的单一方法IStringable提供的基本格式设置支持与 Object.ToString提供的基本格式设置支持相媲美。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. 若要防止歧义,不应在托管类型上实现IStringableTo prevent ambiguity, you should not implement IStringable on managed types.

当本机代码或使用 JavaScript 或C++/cx 等语言编写的代码调用托管对象时,它们看起来实现了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自动将调用路由到事件IStringable中的 Object.ToStringThe common language runtime will automatically route calls from IStringable.ToString to Object.ToString in the event IStringable is not implemented on the managed object.

警告

由于公共语言运行时自动实现 Windows 应用商店Windows Store 应用中所有托管类型的IStringable ,因此,我们建议你不要提供自己的IStringable实现。Because 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. Windows 运行时Windows Runtime、/Cx 或 JavaScript 调用 ToString 时, C++实现 IStringable 可能会导致意外的行为。Implementing IStringable may result in unintended behavior when calling ToString from the Windows 运行时Windows Runtime, C++/CX, or JavaScript.

如果选择在 Windows 运行时Windows Runtime 组件中导出的公共托管类型中实现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  
    

    in C#, or

    Public Class NewClass : Implements IStringable  
    

    口。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实现的托管类型的调用可能会产生意外行为。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 或空字符串。- 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.

-如果你的类型实现了分析方法(或 ParseTryParse 方法、构造函数或从字符串实例化类型实例的其他静态方法),则应确保 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.

适用于

另请参阅