Convert (Clase)
Ensamblado: mscorlib (en mscorlib.dll)
Esta clase devuelve un tipo cuyo valor es equivalente al valor de un tipo especificado. Los tipos base que se admiten son Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime y String.
Existe un método de conversión para convertir todos y cada uno de los tipos base en los demás tipos base. Sin embargo, la operación de conversión real efectuada queda incluida en tres categorías:
-
La conversión de un tipo en sí mismo devuelve dicho tipo. No se lleva a cabo realmente ninguna conversión.
-
La conversión que no puede producir un resultado significativo produce una excepción InvalidCastException. No se lleva a cabo realmente ninguna conversión. Las conversiones de Char en Boolean, Single, Double, Decimal o DateTime, y de estos tipos en Char producen una excepción. Las conversiones de DateTime en cualquier tipo excepto String, y de cualquier tipo excepto String en DateTime producen una excepción.
-
Los tipos base no descritos anteriormente pueden ser objeto de conversiones a y desde cualquier otro tipo base.
No se producirá una excepción si la conversión de un tipo numérico produce una pérdida de precisión, es decir, la pérdida de algunos de los dígitos menos significativos. Sin embargo, la excepción se producirá si el resultado es mayor de lo que puede representar el tipo de valor devuelto del método de conversión.
Por ejemplo, cuando un tipo Double se convierte en un tipo Single, se puede producir una pérdida de precisión pero no se produce ninguna excepción. Sin embargo, si la magnitud del tipo Double es demasiado grande para que un tipo Single lo represente, se produce una excepción de desbordamiento.
Existe un conjunto de métodos que admiten la conversión de una matriz de bytes en y desde un tipo String o una matriz de caracteres Unicode formada por dígitos de base 64. Los datos expresados como dígitos de base 64 se pueden transmitir fácilmente en canales de datos que sólo pueden transmitir caracteres de 7 bits.
Algunos de los métodos de esta clase toman un objeto de parámetro que implementa la interfaz IFormatProvider. Este parámetro puede proporcionar información de formato específica de la referencia cultural para ayudar en el proceso de conversión. Los tipos de valor base pasan por alto este parámetro, pero los tipos definidos por el usuario que implementan IConvertible pueden tenerlo en cuenta.
Para obtener más información sobre los tipos de valor base, vea el tema correspondiente que aparece en la sección Vea también.
En el siguiente ejemplo de código, se muestran algunos de los métodos de conversión de la clase Convert, entre los que se incluyen ToInt32, ToBoolean y ToString.
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
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)));
En el ejemplo de código siguiente se muestran algunos de los métodos de conversión de la clase Convert.
// 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 */
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition
.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.