Object.ToString 方法 (System)

您所在的位置:网站首页 null的tostring Object.ToString 方法 (System)

Object.ToString 方法 (System)

#Object.ToString 方法 (System) | 来源: 网络整理| 查看: 265

Object.ToString 方法 参考 定义 命名空间: System 程序集:System.Runtime.dll 程序集:mscorlib.dll 程序集:netstandard.dll

重要

一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,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 返回 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 list = new List(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 接口的对象,则可以使用 foreach C# 中的 语句或 For Each...Next Visual Basic 中的 构造枚举其元素。

如果类不是 sealed 在 C#) 中 (,也不是 NotInheritable 在 Visual Basic) 中 (,则可以开发一个从要自定义其 Object.ToString 方法的基类继承的包装类。 这至少需要执行以下操作:

实现任何必要的构造函数。 派生类不继承其基类构造函数。

Object.ToString重写 方法以返回所需的结果字符串。

以下示例为 List 类定义包装类。 它重写 Object.ToString 方法以显示集合中每个方法的值,而不是完全限定的类型名称。

using System; using System.Collections.Generic; public class CList : List { public CList(IEnumerable 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(); 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() override this.ToString() = let mutable retVal = String.Empty for item in this do if String.IsNullOrEmpty retVal then retVal


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3