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中格式设置支持的信息,请参阅格式化类型。) 方法的默认实现Object.ToString返回对象的类型的完全限定名称。
重要
你可能已按照另一种类型的成员列表中的链接访问此页面。 这是因为该类型不会重写 Object.ToString。 而是继承方法的功能 Object.ToString 。
类型经常重写 Object.ToString 方法,以提供更合适的特定类型的字符串表示形式。 类型还经常重载 Object.ToString 该方法,以提供对格式字符串或区域性敏感的格式设置的支持。
本部分内容:
default 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 方法以返回表示对象实例的字符串。 例如,基类型,例如CharInt32,并提供StringToString返回对象所表示值的字符串形式的实现。 下面的示例定义一个类, 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中的构造来枚举其元素。如果类在 C#) 中未
sealed
(,或者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方法 (,即,Visual Basic) 中的 C#) 或模块 (中的扩展类 (不能有一个名为
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 运行时 (提供支持的一部分,请参阅Windows应用商店应用和Windows 运行时) .NET Framework支持。 Windows 运行时中的类不会继承Object,也不始终实现。ToString 但是,在 C# 或Visual Basic代码中使用它们时,它们始终具有ToString和Equals(Object)GetHashCode方法,.NET Framework为这些方法提供默认行为。
从 .NET Framework 4.5.1 开始,公共语言运行时在Windows 运行时对象上使用 IStringable.ToString,然后再回退到默认实现。Object.ToString
备注
Windows 运行时用 C# 或Visual Basic编写的类可以替代ToString该方法。
Windows 运行时和 IStringable 接口
从Windows 8.1开始,Windows 运行时包括一个 IStringable 接口,该接口的单个方法 IStringable.ToString 提供与提供的Object.ToString类似的基本格式支持。 为防止歧义,不应在托管类型上实现 IStringable 。
当托管对象由本机代码或以 JavaScript 或 C++/CX 等语言编写的代码调用时,它们似乎实现了 IStringable。 公共语言运行时会自动将来自 IStringable.ToString 的调用路由到 Object.ToString 未在托管对象上实现 IStringable 。
警告
由于公共语言运行时自动实现 Windows Store 应用中所有托管类型的 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() 的字符串可以转换为对象实例。