Object.ToString 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回表示当前对象的字符串。
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
返回
表示当前对象的字符串。
注解
Object.ToString是.NET Framework中的主要格式设置方法。 它将对象转换为其字符串表示形式,使其适合显示。 (有关.NET Framework中格式设置支持的信息,请参阅 Formatting Types。) 方法的默认实现Object.ToString返回对象的类型的完全限定名称。
重要
你可能已通过从另一种类型的成员列表中访问此页的链接。 这是因为该类型不重写 Object.ToString。 相反,它继承 方法的功能 Object.ToString 。
类型经常重写 方法, Object.ToString 以提供特定类型的更合适的字符串表示形式。 类型还经常重载 Object.ToString 方法,以提供对格式字符串或区分区域性的格式的支持。
本部分内容:
默认的 Object.ToString () 方法
重写 Object.ToString () 方法
重载 ToString 方法
扩展 Object.ToString 方法
Windows 运行时说明
默认的 Object.ToString () 方法
方法的默认实现 ToString 返回 类型的完全限定名称 Object,如以下示例所示。
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
由于 Object 是 .NET Framework中所有引用类型的基类,因此此行为由不重写 方法的ToString引用类型继承。 下面的示例对此进行了演示。 它定义一个名为 的 Object1
类,该类接受所有 Object 成员的默认实现。 其 ToString 方法返回对象的完全限定类型名称。
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
重写 Object.ToString () 方法
类型通常重写 方法以 Object.ToString 返回表示对象实例的字符串。 例如,基类型(如 Char、 Int32和 String )提供 ToString 返回对象所表示值的字符串形式的实现。 下面的示例定义一个类 , Object2
该类重写 ToString 方法以返回类型名称及其值。
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
下表列出了 .NET 中的类型类别,并指示它们是否重写 Object.ToString 方法。
类型类别 | Overrides Object.ToString () | 行为 |
---|---|---|
类 | 不适用 | 不适用 |
结构 | 是 (ValueType.ToString) | 与 Object.ToString() 相同 |
枚举 | 是 (Enum.ToString()) | 成员名称 |
接口 | 否 | 不适用 |
委托 | 否 | 不适用 |
有关重写 ToString的其他信息,请参阅继承者说明部分。
重载 ToString 方法
除了重写无 Object.ToString() 参数方法外,许多类型还重载 ToString
方法以提供接受参数的方法版本。 大多数情况下,这样做是为了提供对变量格式设置和区分区域性的格式设置的支持。
下面的示例重载 方法以 ToString
返回一个结果字符串,其中包含类的各个字段 Automobile
的值。 它定义四个格式字符串:G,返回模型名称和年份;D,返回模型名称、年份和门数;C,返回模型名称、年份和柱面数;和 A,返回包含所有四个字段值的字符串。
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
以下示例调用重载 Decimal.ToString(String, IFormatProvider) 方法以显示货币值的区域性敏感格式。
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
有关格式字符串和区分区域性的格式的详细信息,请参阅 格式设置类型。 有关数值支持的格式字符串,请参阅 标准数字格式字符串 和 自定义数字格式字符串。 有关日期和时间值支持的格式字符串,请参阅 标准日期和时间格式字符串 和 自定义日期和时间格式字符串。
扩展 Object.ToString 方法
由于类型继承默认 Object.ToString 方法,因此你可能会发现其行为不可取,并希望对其进行更改。 对于数组和集合类尤其如此。 虽然你可能希望 ToString
数组或集合类的 方法显示其成员的值,但它改为显示类型完全限定的类型名称,如以下示例所示。
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]
有多个选项可用于生成所需的结果字符串。
如果类型是数组、集合对象或实现 IEnumerable 或 IEnumerable<T> 接口的对象,则可以使用
foreach
C# 中的 语句或For Each...Next
Visual Basic 中的 构造枚举其元素。如果类不是
sealed
在 C#) 中 (,也不是NotInheritable
在 Visual Basic) 中 (,则可以开发一个从要自定义其 Object.ToString 方法的基类继承的包装类。 这至少需要执行以下操作:实现任何必要的构造函数。 派生类不继承其基类构造函数。
Object.ToString重写 方法以返回所需的结果字符串。
以下示例为 List<T> 类定义包装类。 它重写 Object.ToString 方法以显示集合中每个方法的值,而不是完全限定的类型名称。
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
开发返回所需结果字符串的 扩展方法 。 请注意,不能以这种方式替代默认 Object.ToString 方法, (也就是说,C#) 中的扩展类或 Visual Basic 中的模块 (中的扩展类 (,) 不能使用名为
ToString
的无参数方法来代替原始类型的ToString
方法。 你必须为无ToString
参数替换提供一些其他名称。下面的示例定义了两个扩展 List<T> 类的方法:无
ToString2
参数方法和ToString
具有 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 }
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 }
Windows 运行时说明
当你对 Windows 运行时 中的类调用 ToString 方法时,它将为不重写 ToString的类提供默认行为。 这是.NET Framework为Windows 运行时 (.NET Framework Windows 应用商店应用和Windows 运行时) 提供支持的一部分。 Windows 运行时 中的类不继承 Object,并且不始终实现 ToString。 但是,当你在 C# 或 Visual Basic 代码中使用它们时,它们似乎始终具有 ToString、 Equals(Object)和 GetHashCode 方法,并且.NET Framework为这些方法提供默认行为。
从 .NET Framework 4.5.1 开始,公共语言运行时在Windows 运行时对象上使用 IStringable.ToString,然后回退到 的默认实现Object.ToString。
注意
用 C# 或 Visual Basic 编写的Windows 运行时类可以替代 ToString 方法。
Windows 运行时和 IStringable 接口
从 Windows 8.1 开始,Windows 运行时包括一个 IStringable 接口,其单个方法 IStringable.ToString 提供的基本格式设置支持与 提供的Object.ToString格式设置支持相当。 为防止歧义性,不应在托管类型上实现 IStringable 。
当托管对象由本机代码或用 JavaScript 或 C++/CX 等语言编写的代码调用时,它们似乎实现了 IStringable。 如果未在托管对象上实现 IStringable,公共语言运行时会自动将调用从 IStringable.ToString 路由到 Object.ToString 。
警告
由于公共语言运行时会自动为 Windows 应用商店应用中的所有托管类型实现 IStringable ,因此我们建议你不要提供自己的 IStringable
实现。 从 IStringable
Windows 运行时、C++/CX 或 JavaScript 调用 ToString
时,实现可能会导致意外行为。
如果选择在Windows 运行时组件中导出的公共托管类型中实现 IStringable,则以下限制适用:
只能在“类实现”关系中定义 IStringable 接口,如下所示:
public class NewClass : IStringable
Public Class NewClass : Implements IStringable
不能在接口上实现 IStringable 。
不能将参数声明为 IStringable 类型。
IStringable 不能是方法、属性或字段的返回类型。
不能通过使用如下所示的方法定义在基类中隐藏 IStringable 实现:
public class NewClass : IStringable { public new string ToString() { return "New ToString in NewClass"; } }
相反,IStringable.ToString 实现必须始终重写基类实现。 只能通过对强类型类实例调用
ToString
实现来隐藏该实现。
请注意,在各种条件下,从本机代码调用实现 IStringable 或隐藏其 ToString 实现的托管类型可能会产生意外行为。
继承者说明
实现自己的类型时,应重写 ToString() 方法以返回对这些类型有意义的值。 需要比 ToString() 提供的更多格式控制的派生类可以实现 IFormattable 接口。 其 ToString(String, IFormatProvider) 方法使你可以定义控制格式设置的格式字符串,并使用 IFormatProvider 可以提供特定于区域性的格式设置的对象。
方法的 ToString() 替代应遵循以下准则:
返回的字符串应该友好且可由人类读取。
返回的字符串应唯一标识对象实例的值。
返回的字符串应尽可能短,以便它适合由调试器显示。
重写 ToString() 不应返回 Empty 或 null 字符串。
替代 ToString() 不应引发异常。
如果实例的字符串表示形式区分区域性,或者可以通过多种方式设置格式,则实现 IFormattable 接口。
如果返回的字符串包含敏感信息,应首先请求适当的权限。 如果需求成功,可以返回敏感信息;否则,应返回排除敏感信息的字符串。
替代 ToString() 应没有可观察到的副作用,以避免调试时出现复杂情况。 例如,对 方法的 ToString() 调用不应更改实例字段的值。
如果类型实现分析方法 (或 或
Parse
TryParse
方法、构造函数或从字符串) 实例化类型的实例的其他静态方法,则应确保该方法返回的 ToString() 字符串可以转换为对象实例。