Convert-Klasse

Konvertiert einen Basisdatentyp in einen anderen Basisdatentyp.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public NotInheritable Class Convert
'Usage
Auf die Member einer statischen Klassen wird direkt ohne Instanz der Klasse zugegriffen.
public static class Convert
public ref class Convert abstract sealed
public final class Convert
public final class Convert

Hinweise

Diese Klasse gibt einen Typ zurück, dessen Wert dem Wert eines angegebenen Typs entspricht. Die unterstützten Basisdatentypen sind Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime und String.

Es gibt eine Konvertierungsmethode, mit der jeder Basistyp in jeden anderen Basistyp konvertiert werden kann. Es gilt aber, dass jeder ausgeführte Konvertierungsvorgang in eine von drei Kategorien fällt:

  • Eine Konvertierung von einem Typ in sich selbst gibt einfach diesen Typ zurück. Es wird keine Konvertierung ausgeführt.

  • Eine Konvertierung, die kein brauchbares Ergebnis liefern kann, löst die InvalidCastException aus. Es wird keine Konvertierung ausgeführt. Eine Ausnahme wird für Konvertierungen von Char in Boolean , Single , Double , Decimal oder DateTime und von Konvertierungen dieser Typen in Char ausgelöst. Eine Ausnahme wird für Konvertierungen von DateTime in jeden Typ mit Ausnahme von String und Konvertierungen von jedem Typ, ausgenommen String, in DateTime ausgelöst.

  • Jeder Basistyp, der nicht in die gerade beschriebenen Beschränkungen fällt, kann in jeden und von jedem anderen Basistyp konvertiert werden.

Es wird keine Ausnahme ausgelöst, wenn die Konvertierung eines numerischen Typs zu einem Genauigkeitsverlust (d. h. zum Verlust eines Teiles der am wenigsten signifikanten Ziffern) führt. Allerdings wird eine Ausnahme ausgelöst, wenn das Ergebnis so groß ist, dass es nicht durch den Typ des Rückgabewerts dieser speziellen Konvertierungsmethode dargestellt werden kann.

Wenn z. B. ein Double in einen Single konvertiert wird, kann ein Genauigkeitsverlust auftreten, aber es wird keine Ausnahme ausgelöst. Wenn der Double allerdings so groß ist, dass er nicht als Single dargestellt werden kann, wird eine Ausnahme wegen Überlaufs ausgelöst.

Eine Gruppe von Methoden unterstützt das Konvertieren zwischen einem Bytearray und einem String oder einem Array von Unicode-Zeichen, die aus Base-64-Ziffernzeichen bestehen. Als Base-64-Ziffern dargestellte Daten können bequem über Datenchannels übermittelt werden, die nur 7-Bit-Zeichen übertragen können.

Einige Methoden dieser Klasse akzeptieren ein Parameterobjekt, das die IFormatProvider-Schnittstelle implementiert. Dieser Parameter kann beim Konvertierungsvorgang hilfreiche kulturabhängige Formatierungsinformationen liefern. Bei Basiswerttypen wird dieser Parameter ignoriert; ein benutzerdefinierter Typ, der IConvertible implementiert, kann ihn jedoch beachten.

Weitere Informationen über Basiswerttypen finden Sie unter dem entsprechenden Thema im "Siehe auch"-Abschnitt.

Beispiel

Im folgenden Codebeispiel werden einige der Konvertierungsmethoden in der Convert-Klasse veranschaulicht, einschließlich ToInt32, ToBoolean und ToString.

Dim dNumber As Double
dNumber = 23.15

Try
   ' Returns 23
   Dim iNumber As Integer
   iNumber = System.Convert.ToInt32(dNumber)
Catch exp As System.OverflowException
   System.Console.WriteLine("Overflow in double to int conversion.")
End Try

' Returns True
Dim bNumber As Boolean
bNumber = System.Convert.ToBoolean(dNumber)

' Returns "23.15"
Dim strNumber As String
strNumber = System.Convert.ToString(dNumber)

Try
   ' Returns '2'
   Dim chrNumber As Char
   chrNumber = System.Convert.ToChar(strNumber.Chars(1))
Catch exp As System.ArgumentNullException
   System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
   System.Console.WriteLine("String length is greater than 1.")
End Try

' System.Console.ReadLine() returns a string and it
' must be converted.
Dim newInteger As Integer
newInteger = 0
Try
   System.Console.WriteLine("Enter an integer:")
   newInteger = System.Convert.ToInt32(System.Console.ReadLine())
Catch exp As System.ArgumentNullException
   System.Console.WriteLine("String is null.")
Catch exp As System.FormatException
   System.Console.WriteLine("String does not consist of an " + _
       "optional sign followed by a series of digits.")
Catch exp As System.OverflowException
   System.Console.WriteLine("Overflow in string to int conversion.")
End Try

System.Console.WriteLine("Your integer as a double is {0}", _
                         System.Convert.ToDouble(newInteger))
double dNumber = 23.15;

try {
    // Returns 23
    int    iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException) {
    System.Console.WriteLine(
                "Overflow in double to int conversion.");
}
// Returns True
bool   bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
string strNumber = System.Convert.ToString(dNumber);

try {
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber[0]);
} 
catch (System.ArgumentNullException) {
    System.Console.WriteLine("String is null");
}
catch (System.FormatException) {
    System.Console.WriteLine("String length is greater than 1.");
}

// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;
try {
    System.Console.WriteLine("Enter an integer:");
    newInteger = System.Convert.ToInt32(
                        System.Console.ReadLine());
}
catch (System.ArgumentNullException) {
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException) {
    System.Console.WriteLine("String does not consist of an " +
                    "optional sign followed by a series of digits.");
} 
catch (System.OverflowException) {
    System.Console.WriteLine(
    "Overflow in string to int conversion.");
}

System.Console.WriteLine("Your integer as a double is {0}",
                         System.Convert.ToDouble(newInteger));
Double dNumber = 23.15;

try
{
   // Returns 23
   Int32 iNumber = Convert::ToInt32( dNumber );
}
catch ( OverflowException^ ) 
{
   Console::WriteLine(
      "Overflow in Double to Int32 conversion" );
}
// Returns True
Boolean bNumber = Convert::ToBoolean( dNumber );

// Returns "23.15"
String^ strNumber = Convert::ToString( dNumber );

try
{
   // Returns '2'
   Char chrNumber = Convert::ToChar( strNumber->Substring( 0, 1 ) );
}
catch ( ArgumentNullException^ ) 
{
   Console::WriteLine(  "String is null" );
}
catch ( FormatException^ ) 
{
   Console::WriteLine(  "String length is greater than 1" );
}

// System::Console::ReadLine() returns a string and it
// must be converted.
Int32 newInteger = 0;
try
{
   Console::WriteLine(  "Enter an integer:" );
   newInteger = Convert::ToInt32( System::Console::ReadLine() );
}
catch ( ArgumentNullException^ ) 
{
   Console::WriteLine(  "String is null" );
}
catch ( FormatException^ ) 
{
   Console::WriteLine(  "String does not consist of an " +
      "optional sign followed by a series of digits" );
}
catch ( OverflowException^ ) 
{
   Console::WriteLine(  "Overflow in string to Int32 conversion" );
}

Console::WriteLine( "Your integer as a Double is {0}",
   Convert::ToDouble( newInteger ) );
double dNumber = 23.15;

try {        
    // Returns 23
    int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in double to int conversion.");
}

// Returns True
boolean bNumber = System.Convert.ToBoolean(dNumber);

// Returns "23.15"
String strNumber = System.Convert.ToString(dNumber);

try {        
    // Returns '2'
    char chrNumber = System.Convert.ToChar(strNumber.get_Chars(0));
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine("String length is greater than 1.");
}

// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;

try {        
    System.Console.WriteLine("Enter an integer:");
    newInteger = System.Convert.ToInt32(System.Console.ReadLine());
}
catch (System.ArgumentNullException exp) {        
    System.Console.WriteLine("String is null.");
}
catch (System.FormatException exp) {        
    System.Console.WriteLine(("String does not consist of an " 
        + "optional sign followed by a series of digits."));
}
catch (System.OverflowException exp) {        
    System.Console.WriteLine("Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}", 
    System.Convert.ToString(System.Convert.ToDouble(newInteger)));

Im folgenden Codebeispiel werden verschiedene Konvertierungsmethoden in der Convert-Klasse veranschaulicht.

' Sample for the Convert class summary.
Imports System

Class Sample
   Public Shared Sub Main()
      Dim nl As String = Environment.NewLine
      Dim str As String = "{0}Return the Int64 equivalent of the following base types:{0}"
      Dim xBool As Boolean = False
      Dim xShort As Short = 1
      Dim xInt As Integer = 2
      Dim xLong As Long = 3
      Dim xSingle As Single = 4F
      Dim xDouble As Double = 5.0
      Dim xDecimal As Decimal = 6D
      Dim xString As String = "7"
      Dim xChar As Char = "8"c ' '8' = hexadecimal 38 = decimal 56
      Dim xByte As Byte = 9
      
      '  The following types are not CLS-compliant.
      ' Dim xUshort As System.UInt16 = 120
      ' Dim xUint As System.UInt32 = 121
      ' Dim xUlong As System.UInt64 = 122
      ' Dim xSbyte As System.SByte = 123
      
      '  The following type cannot be converted to an Int64.
      '  Dim xDateTime As System.DateTime = DateTime.Now

      Console.WriteLine(str, nl)
      Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool))
      Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort))
      Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt))
      Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong))
      Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle))
      Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble))
      Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal))
      Console.WriteLine("String:   {0}", Convert.ToInt64(xString))
      Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar))
      Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte))
      Console.WriteLine("DateTime: There is no example of this conversion because")
      Console.WriteLine("          a DateTime cannot be converted to an Int64.")
      '
      Console.Write("{0}The following types are not supported: ", nl)
      Console.WriteLine("UInt16, UInt32, UInt64, and SByte")
   End Sub 'Main
End Class 'Sample
'
'This example produces the following results:
'
'Return the Int64 equivalent of the following base types:
'
'Boolean:  0
'Int16:    1
'Int32:    2
'Int64:    3
'Single:   4
'Double:   5
'Decimal:  6
'String:   7
'Char:     56
'Byte:     9
'DateTime: There is no example of this conversion because
'          a DateTime cannot be converted to an Int64.
'
'The following types are not supported: UInt16, UInt32, UInt64, and SByte
'
// Sample for the Convert class summary.
using System;

class Sample 
{
    public static void Main() 
    {
    string nl = Environment.NewLine;
    string str = "{0}Return the Int64 equivalent of the following base types:{0}";
    bool    xBool = false;
    short   xShort = 1;
    int     xInt   = 2;
    long    xLong  = 3;
    float   xSingle = 4.0f;
    double  xDouble = 5.0;
    decimal xDecimal = 6.0m;
    string  xString = "7";
    char    xChar   = '8'; // '8' = hexadecimal 38 = decimal 56
    byte    xByte  =  9;

//  The following types are not CLS-compliant.
    ushort  xUshort = 120;   
    uint    xUint =   121;
    ulong   xUlong =  122;
    sbyte   xSbyte  = 123;

//  The following type cannot be converted to an Int64.
//  DateTime xDateTime = DateTime.Now;

    Console.WriteLine(str, nl);
    Console.WriteLine("Boolean:  {0}", Convert.ToInt64(xBool));
    Console.WriteLine("Int16:    {0}", Convert.ToInt64(xShort));
    Console.WriteLine("Int32:    {0}", Convert.ToInt64(xInt));
    Console.WriteLine("Int64:    {0}", Convert.ToInt64(xLong));
    Console.WriteLine("Single:   {0}", Convert.ToInt64(xSingle));
    Console.WriteLine("Double:   {0}", Convert.ToInt64(xDouble));
    Console.WriteLine("Decimal:  {0}", Convert.ToInt64(xDecimal));
    Console.WriteLine("String:   {0}", Convert.ToInt64(xString));
    Console.WriteLine("Char:     {0}", Convert.ToInt64(xChar));
    Console.WriteLine("Byte:     {0}", Convert.ToInt64(xByte));
    Console.WriteLine("DateTime: There is no example of this conversion because");
    Console.WriteLine("          a DateTime cannot be converted to an Int64.");
//
    Console.WriteLine("{0}The following types are not CLS-compliant.{0}", nl);
    Console.WriteLine("UInt16:   {0}", Convert.ToInt64(xUshort));
    Console.WriteLine("UInt32:   {0}", Convert.ToInt64(xUint));
    Console.WriteLine("UInt64:   {0}", Convert.ToInt64(xUlong));
    Console.WriteLine("SByte:    {0}", Convert.ToInt64(xSbyte));
    }
}
/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
          a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/
// Sample for the Convert class summary.
using namespace System;
int main()
{
   String^ nl = Environment::NewLine;
   String^ str = " {0}Return the Int64 equivalent of the following base types: {0}";
   bool xBool = false;
   short xShort = 1;
   int xInt = 2;
   long xLong = 3;
   float xSingle = 4.0f;
   double xDouble = 5.0;
   Decimal xDecimal = Decimal(6.0);
   String^ xString = "7";
   char xChar = '8'; // '8' = hexadecimal 38 = decimal 56

   Byte xByte = 9;
   
   //  The following types are not CLS-compliant.
   UInt16 xUshort = 120;
   UInt32 xUint = 121;
   UInt64 xUlong = 122;
   SByte xSbyte = 123;
   
   //  The following type cannot be converted to an Int64.
   //  DateTime xDateTime = DateTime::Now;
   Console::WriteLine( str, nl );
   Console::WriteLine( "Boolean: {0}", Convert::ToInt64( xBool ) );
   Console::WriteLine( "Int16: {0}", Convert::ToInt64( xShort ) );
   Console::WriteLine( "Int32: {0}", Convert::ToInt64( xInt ) );
   Console::WriteLine( "Int64: {0}", Convert::ToInt64( xLong ) );
   Console::WriteLine( "Single: {0}", Convert::ToInt64( xSingle ) );
   Console::WriteLine( "Double: {0}", Convert::ToInt64( xDouble ) );
   Console::WriteLine( "Decimal: {0}", Convert::ToInt64( xDecimal ) );
   Console::WriteLine( "String: {0}", Convert::ToInt64( xString ) );
   Console::WriteLine( "Char: {0}", Convert::ToInt64( xChar ) );
   Console::WriteLine( "Byte: {0}", Convert::ToInt64( xByte ) );
   Console::WriteLine( "DateTime: There is no example of this conversion because" );
   Console::WriteLine( "          a DateTime cannot be converted to an Int64." );
   
   //
   Console::WriteLine( " {0}The following types are not CLS-compliant. {0}", nl );
   Console::WriteLine( "UInt16: {0}", Convert::ToInt64( xUshort ) );
   Console::WriteLine( "UInt32: {0}", Convert::ToInt64( xUint ) );
   Console::WriteLine( "UInt64: {0}", Convert::ToInt64( xUlong ) );
   Console::WriteLine( "SByte: {0}", Convert::ToInt64( xSbyte ) );
}

/*
This example produces the following results:

Return the Int64 equivalent of the following base types:

Boolean:  0
Int16:    1
Int32:    2
Int64:    3
Single:   4
Double:   5
Decimal:  6
String:   7
Char:     56
Byte:     9
DateTime: There is no example of this conversion because
a DateTime cannot be converted to an Int64.

The following types are not CLS-compliant.

UInt16:   120
UInt32:   121
UInt64:   122
SByte:    123
*/

Vererbungshierarchie

System.Object
  System.Convert

Threadsicherheit

Alle öffentlichen statischen (Shared in Visual Basic) Member dieses Typs sind threadsicher. Bei Instanzmembern ist die Threadsicherheit nicht gewährleistet.

Plattformen

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

Versionsinformationen

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0

.NET Compact Framework

Unterstützt in: 2.0, 1.0

Siehe auch

Referenz

Convert-Member
System-Namespace
Object
SByte
Int16
Int32
Int64
Byte-Struktur
UInt16
UInt32
UInt64
Single
Double
Decimal
Boolean-Struktur
Char-Struktur
String