ValueType.ToString Метод
Определение
Возвращает полное имя типа этого экземпляра.Returns the fully qualified type name of this instance.
public:
override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String
Возвраты
Полное имя типа.The fully qualified type name.
Комментарии
Метод ValueType.ToString переопределяет метод Object.ToString и предоставляет реализацию метода ToString
для типов значений по умолчанию.The ValueType.ToString method overrides the Object.ToString method and provides the default implementation of the ToString
method for value types. (Типы значений — это типы, определяемые ключевым словом @no__t- C#0 в, а также конструкцией Structure
... End Structure
в Visual Basic.) Функционально, однако, реализация — это то же самое, что Object.ToString: метод возвращает полное имя типа.(Value types are types defined by the struct
keyword in C#, and by the Structure
...End Structure
construct in Visual Basic.) Functionally, however, the implementation is that same as that of Object.ToString: the method returns the fully qualified type name.
Типы значений, определяемые ключевым словом struct
C# в, и Structure
... End Structure
в Visual Basic обычно переопределяют метод ValueType.ToString, чтобы обеспечить более осмысленное строковое представление типа значения.Value types defined by the struct
keyword in C# and the Structure
...End Structure
construct in Visual Basic typically override the ValueType.ToString method to provide a more meaningful string representation of the value type. В следующем примере демонстрируется это различие.The following example illustrates the difference. Он определяет два типа значений: EmployeeA
и EmployeeB
, создает экземпляр каждого и вызывает его метод ToString
.It defines two value types, EmployeeA
and EmployeeB
, creates an instance of each, and calls its ToString
method. Поскольку структура EmployeeA
не переопределяет метод ValueType.ToString, он отображает только полное имя типа.Because the EmployeeA
structure does not override the ValueType.ToString method, it displays only the fully qualified type name. С другой стороны, метод EmployeeB.ToString
предоставляет осмысленные сведения об объекте.The EmployeeB.ToString
method, on the other hand, provides meaningful information about the object.
using System;
using Corporate.EmployeeObjects;
public class Example
{
public static void Main()
{
var empA = new EmployeeA{ Name = "Robert",};
Console.WriteLine(empA.ToString());
var empB = new EmployeeB{ Name = "Robert",};
Console.WriteLine(empB.ToString());
}
}
namespace Corporate.EmployeeObjects
{
public struct EmployeeA
{
public String Name { get; set; }
}
public struct EmployeeB
{
public String Name { get; set; }
public override String ToString()
{
return Name;
}
}
}
// The example displays the following output:
// Corporate.EmployeeObjects.EmployeeA
// Robert
Imports Corporate.EmployeeObjects
Module Example
Public Sub Main()
Dim empA As New EmployeeA With { .Name = "Robert" }
Console.WriteLine(empA.ToString())
Dim empB = new EmployeeB With { .Name = "Robert" }
Console.WriteLine(empB.ToString())
End Sub
End Module
Namespace Corporate.EmployeeObjects
Public Structure EmployeeA
Public Property Name As String
End Structure
Public Structure EmployeeB
Public Property Name As String
Public Overrides Function ToString() As String
Return Name
End Function
End Structure
End Namespace
' The example displays the following output:
' Corporate.EmployeeObjects.EmployeeA
' Robert
Обратите внимание, что, хотя типы перечисления также являются типами значений, они являются производными от класса Enum, который переопределяет ValueType.ToString.Note that, although enumeration types are also value types, they derive from the Enum class, which overrides ValueType.ToString.
Примечания для среда выполнения WindowsNotes for the Windows Runtime
При вызове метода ToString для структуры Среда выполнения WindowsWindows Runtime он предоставляет поведение по умолчанию для типов значений, которые не переопределяют ToString.When you call the ToString method on a Среда выполнения WindowsWindows Runtime structure, it provides the default behavior for value types that don't override ToString. Это является частью поддержки, которую .NET Framework предоставляет для Среда выполнения WindowsWindows Runtime (см. раздел поддержка .NET Framework для приложений Магазина Windows и среда выполнения Windows).This is part of the support that the .NET Framework provides for the Среда выполнения WindowsWindows Runtime (see .NET Framework Support for Windows Store Apps and Windows Runtime). Среда выполнения WindowsWindows Runtime структуры не могут переопределять ToString, даже если они написаны с помощью C# или Visual Basic, так как они не могут иметь методы.structures can't override ToString, even if they're written with C# or Visual Basic, because they can't have methods. (Кроме того, структуры в самом Среда выполнения WindowsWindows Runtime не наследуют ValueType). Однако они выглядят как ToString, Equals и GetHashCode, когда они используются в коде C# или Visual Basic, а .NET Framework предоставляет поведение по умолчанию для этих методов.(In addition, structures in the Среда выполнения WindowsWindows Runtime itself don't inherit ValueType.) However, they appear to have ToString, Equals, and GetHashCode methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods.