Leer en inglés

Compartir a través de


Convert.ChangeType Método

Definición

Devuelve un objeto de un tipo especificado cuyo valor es equivalente a un objeto especificado.

Sobrecargas

ChangeType(Object, Type)

Devuelve un objeto del tipo especificado y cuyo valor es equivalente al objeto especificado.

ChangeType(Object, TypeCode)

Devuelve un objeto del tipo especificado cuyo valor es equivalente al objeto especificado.

ChangeType(Object, Type, IFormatProvider)

Devuelve un objeto del tipo especificado cuyo valor es equivalente al objeto especificado. Un parámetro proporciona información de formato específica de la referencia cultural.

ChangeType(Object, TypeCode, IFormatProvider)

Devuelve un objeto del tipo especificado cuyo valor es equivalente al objeto especificado. Un parámetro proporciona información de formato específica de la referencia cultural.

ChangeType(Object, Type)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

Devuelve un objeto del tipo especificado y cuyo valor es equivalente al objeto especificado.

C#
public static object ChangeType (object value, Type conversionType);
C#
public static object? ChangeType (object? value, Type conversionType);

Parámetros

value
Object

Objeto que implementa la interfaz IConvertible.

conversionType
Type

Tipo de objeto que se va a devolver.

Devoluciones

Objeto cuyo tipo es conversionType y cuyo valor es equivalente a value.

-o-

Referencia nula (Nothing en Visual Basic), si value es null y conversionType no es un tipo de valor.

Excepciones

Esta conversión no se admite.

-o-

value es null y conversionType es un tipo de valor.

-o-

value no implementa la interfaz IConvertible.

value no está en un formato reconocido por conversionType.

value representa un número que está fuera del intervalo de conversionType.

conversionType es null.

Ejemplos

En el ejemplo siguiente se muestra el uso del método ChangeType.

C#
using System;

public class ChangeTypeTest {
    public static void Main() {

        Double d = -2.345;
        int i = (int)Convert.ChangeType(d, typeof(int));

        Console.WriteLine("The double value {0} when converted to an int becomes {1}", d, i);

        string s = "12/12/98";
        DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

        Console.WriteLine("The string value {0} when converted to a Date becomes {1}", s, dt);
    }
}

Comentarios

ChangeType es un método de conversión de uso general que convierte el objeto especificado por value en conversionType. El parámetro value puede ser un objeto de cualquier tipo y conversionType también puede ser un objeto Type que representa cualquier tipo base o personalizado. Para que la conversión se realice correctamente, value debe implementar la interfaz IConvertible, ya que el método simplemente ajusta una llamada a un método IConvertible adecuado. El método requiere que se admita la conversión de value a conversionType.

Este método usa la referencia cultural del subproceso actual para la conversión.

Notas a los autores de las llamadas

El método ChangeType(Object, Type) puede convertir un valor de enumeración a otro tipo. Sin embargo, no puede convertir otro tipo en un valor de enumeración, incluso si el tipo de origen es el tipo subyacente de la enumeración. Para convertir un tipo en un valor de enumeración, use un operador de conversión (en C#) o una función de conversión (en Visual Basic). En el ejemplo siguiente se muestra la conversión a y desde un valor de enumeración de Continent.

C#
using System;

public enum Continent
{
   Africa, Antarctica, Asia, Australia, Europe,
   NorthAmerica, SouthAmerica
};

public class Example
{
   public static void Main()
   {
      // Convert a Continent to a Double.
      Continent cont = Continent.NorthAmerica;
      Console.WriteLine("{0:N2}",
                        Convert.ChangeType(cont, typeof(Double)));

      // Convert a Double to a Continent.
      Double number = 6.0;
      try {
         Console.WriteLine("{0}",
                           Convert.ChangeType(number, typeof(Continent)));
      }
      catch (InvalidCastException) {
         Console.WriteLine("Cannot convert a Double to a Continent");
      }

      Console.WriteLine("{0}", (Continent) number);
   }
}
// The example displays the following output:
//       5.00
//       Cannot convert a Double to a Continent
//       SouthAmerica

El método ChangeType(Object, Type) puede convertir un tipo que acepta valores NULL a otro tipo. Sin embargo, no puede convertir otro tipo en un valor de un tipo que acepta valores NULL, incluso si conversionType es el tipo subyacente del Nullable<T>. Para realizar la conversión, puede usar un operador de conversión (en C#) o una función de conversión (en Visual Basic). En el ejemplo siguiente se muestra la conversión a y desde un tipo que acepta valores NULL.

C#
using System;

public class Example
{
   public static void Main()
   {
      int? intValue1 = 12893;
      double dValue1 = (double) Convert.ChangeType(intValue1, typeof(Double));
      Console.WriteLine("{0} ({1})--> {2} ({3})", intValue1, intValue1.GetType().Name,
                        dValue1, dValue1.GetType().Name);

      float fValue1 = 16.3478f;
      int? intValue2 = (int) fValue1;
      Console.WriteLine("{0} ({1})--> {2} ({3})", fValue1, fValue1.GetType().Name,
                        intValue2, intValue2.GetType().Name);
   }
}
// The example displays the following output:
//    12893 (Int32)--> 12893 (Double)
//    16.3478 (Single)--> 16 (Int32)

Se aplica a

.NET 9 y otras versiones
Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ChangeType(Object, TypeCode)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

Devuelve un objeto del tipo especificado cuyo valor es equivalente al objeto especificado.

C#
public static object? ChangeType (object? value, TypeCode typeCode);
C#
public static object ChangeType (object value, TypeCode typeCode);

Parámetros

value
Object

Objeto que implementa la interfaz IConvertible.

typeCode
TypeCode

Tipo de objeto que se va a devolver.

Devoluciones

Objeto cuyo tipo subyacente es typeCode y cuyo valor es equivalente a value.

-o-

Referencia nula (Nothing en Visual Basic), si value es null y typeCode es Empty, Stringo Object.

Excepciones

Esta conversión no se admite.

-o-

value es null y typeCode especifica un tipo de valor.

-o-

value no implementa la interfaz IConvertible.

value no está en un formato reconocido por el tipo typeCode.

value representa un número que está fuera del intervalo del tipo typeCode.

typeCode no es válido.

Ejemplos

En el ejemplo siguiente se muestra cómo usar el método ChangeType(Object, TypeCode) para cambiar un Object al tipo especificado por el parámetro TypeCode, si es posible.

C#
using System;

public class ChangeTypeTest {
    public static void Main() {

        Double d = -2.345;
        int i = (int)Convert.ChangeType(d, TypeCode.Int32);

        Console.WriteLine("The Double {0} when converted to an Int32 is {1}", d, i);

        string s = "12/12/2009";
        DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

        Console.WriteLine("The String {0} when converted to a Date is {1}", s, dt);
    }
}
// The example displays the following output:
//    The Double -2.345 when converted to an Int32 is -2
//    The String 12/12/2009 when converted to a Date is 12/12/2009 12:00:00 AM

Comentarios

ChangeType(Object, TypeCode) es un método de conversión de uso general que convierte el objeto especificado por value en un tipo predefinido especificado por typeCode. El parámetro value puede ser un objeto de cualquier tipo. Para que la conversión se realice correctamente, value debe implementar la interfaz IConvertible, ya que el método simplemente ajusta una llamada a un método IConvertible adecuado. El método también requiere que se admita la conversión de value a typeCode.

El método ChangeType(Object, TypeCode) no admite la conversión de value a un tipo personalizado. Para realizar esta conversión, llame al método ChangeType(Object, Type).

Se aplica a

.NET 9 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

ChangeType(Object, Type, IFormatProvider)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

Devuelve un objeto del tipo especificado cuyo valor es equivalente al objeto especificado. Un parámetro proporciona información de formato específica de la referencia cultural.

C#
public static object ChangeType (object value, Type conversionType, IFormatProvider provider);
C#
public static object? ChangeType (object? value, Type conversionType, IFormatProvider? provider);

Parámetros

value
Object

Objeto que implementa la interfaz IConvertible.

conversionType
Type

Tipo de objeto que se va a devolver.

provider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

Devoluciones

Objeto cuyo tipo es conversionType y cuyo valor es equivalente a value.

-o-

value, si el Type de value y conversionType son iguales.

-o-

Referencia nula (Nothing en Visual Basic), si value es null y conversionType no es un tipo de valor.

Excepciones

Esta conversión no se admite.

-o-

value es null y conversionType es un tipo de valor.

-o-

value no implementa la interfaz IConvertible.

value no tiene un formato para conversionType reconocido por provider.

value representa un número que está fuera del intervalo de conversionType.

conversionType es null.

Ejemplos

En el ejemplo siguiente se define una clase Temperature que implementa la interfaz IConvertible.

C#
using System;
using System.Globalization;

public class Temperature : IConvertible
{
   private decimal m_Temp;

   public Temperature(decimal temperature)
   {
      this.m_Temp = temperature;
   }

   public decimal Celsius
   {
      get { return this.m_Temp; }
   }

   public decimal Kelvin
   {
      get { return this.m_Temp + 273.15m; }
   }

   public decimal Fahrenheit
   {
      get { return Math.Round((decimal) (this.m_Temp * 9 / 5 + 32), 2); }
   }

   public override string ToString()
   {
      return m_Temp.ToString("N2") + "°C";
   }

   // IConvertible implementations.
   public TypeCode GetTypeCode()
   {
      return TypeCode.Object;
   }

   public bool ToBoolean(IFormatProvider provider)
   {
      if (m_Temp == 0)
         return false;
      else
         return true;
   }

   public byte ToByte(IFormatProvider provider)
   {
      if (m_Temp < Byte.MinValue || m_Temp > Byte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Byte type.",
                                                   this.m_Temp));
      else
         return Decimal.ToByte(this.m_Temp);
   }

   public char ToChar(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to Char conversion is not supported.");
   }

   public DateTime ToDateTime(IFormatProvider provider)
   {
      throw new InvalidCastException("Temperature to DateTime conversion is not supported.");
   }

   public decimal ToDecimal(IFormatProvider provider)
   {
      return this.m_Temp;
   }

   public double ToDouble(IFormatProvider provider)
   {
      return Decimal.ToDouble(this.m_Temp);
   }

   public short ToInt16(IFormatProvider provider)
   {
      if (this.m_Temp < Int16.MinValue || this.m_Temp > Int16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int16 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt16(this.m_Temp);
   }

   public int ToInt32(IFormatProvider provider)
      {
      if (this.m_Temp < Int32.MinValue || this.m_Temp > Int32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int32 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt32(this.m_Temp);
   }

   public long ToInt64(IFormatProvider provider)
   {
      if (this.m_Temp < Int64.MinValue || this.m_Temp > Int64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the Int64 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToInt64(this.m_Temp);
   }

   public sbyte ToSByte(IFormatProvider provider)
   {
      if (this.m_Temp < SByte.MinValue || this.m_Temp > SByte.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the SByte type.",
                                                   this.m_Temp));
      else
         return Decimal.ToSByte(this.m_Temp);
   }

   public float ToSingle(IFormatProvider provider)
   {
      return Decimal.ToSingle(this.m_Temp);
   }

   public string ToString(IFormatProvider provider)
   {
      return m_Temp.ToString("N2", provider) + "°C";
   }

   public object ToType(Type conversionType, IFormatProvider provider)
   {
      switch (Type.GetTypeCode(conversionType))
      {
         case TypeCode.Boolean:
            return this.ToBoolean(null);
         case TypeCode.Byte:
            return this.ToByte(null);
         case TypeCode.Char:
            return this.ToChar(null);
         case TypeCode.DateTime:
            return this.ToDateTime(null);
         case TypeCode.Decimal:
            return this.ToDecimal(null);
         case TypeCode.Double:
            return this.ToDouble(null);
         case TypeCode.Int16:
            return this.ToInt16(null);
         case TypeCode.Int32:
            return this.ToInt32(null);
         case TypeCode.Int64:
            return this.ToInt64(null);
         case TypeCode.Object:
            if (typeof(Temperature).Equals(conversionType))
               return this;
            else
               throw new InvalidCastException(String.Format("Conversion to a {0} is not supported.",
                                                            conversionType.Name));
         case TypeCode.SByte:
            return this.ToSByte(null);
         case TypeCode.Single:
            return this.ToSingle(null);
         case TypeCode.String:
            return this.ToString(provider);
         case TypeCode.UInt16:
            return this.ToUInt16(null);
         case TypeCode.UInt32:
            return this.ToUInt32(null);
         case TypeCode.UInt64:
            return this.ToUInt64(null);
         default:
            throw new InvalidCastException(String.Format("Conversion to {0} is not supported.", conversionType.Name));
      }
   }

   public ushort ToUInt16(IFormatProvider provider)
   {
      if (this.m_Temp < UInt16.MinValue || this.m_Temp > UInt16.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt16 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt16(this.m_Temp);
   }

   public uint ToUInt32(IFormatProvider provider)
   {
      if (this.m_Temp < UInt32.MinValue || this.m_Temp > UInt32.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt32 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt32(this.m_Temp);
   }

   public ulong ToUInt64(IFormatProvider provider)
   {
      if (this.m_Temp < UInt64.MinValue || this.m_Temp > UInt64.MaxValue)
         throw new OverflowException(String.Format("{0} is out of range of the UInt64 type.",
                                                   this.m_Temp));
      else
         return Decimal.ToUInt64(this.m_Temp);
   }
}

En el ejemplo siguiente se crea una instancia de la clase Temperature y se llama al método ChangeType(Object, Type, IFormatProvider) para convertirlo a los tipos numéricos básicos admitidos por .NET y a un String. Muestra que el método ChangeType ajusta una llamada a la implementación de IConvertible del tipo de origen.

C#
public class Example
{
   public static void Main()
   {
      Temperature cool = new Temperature(5);
      Type[] targetTypes = { typeof(SByte), typeof(Int16), typeof(Int32),
                             typeof(Int64), typeof(Byte), typeof(UInt16),
                             typeof(UInt32), typeof(UInt64), typeof(Decimal),
                             typeof(Single), typeof(Double), typeof(String) };
      CultureInfo provider = new CultureInfo("fr-FR");

      foreach (Type targetType in targetTypes)
      {
         try {
            object value = Convert.ChangeType(cool, targetType, provider);
            Console.WriteLine("Converted {0} {1} to {2} {3}.",
                              cool.GetType().Name, cool.ToString(),
                              targetType.Name, value);
         }
         catch (InvalidCastException) {
            Console.WriteLine("Unsupported {0} --> {1} conversion.",
                              cool.GetType().Name, targetType.Name);
         }
         catch (OverflowException) {
            Console.WriteLine("{0} is out of range of the {1} type.",
                              cool, targetType.Name);
         }
      }
   }
}
// The example dosplays the following output:
//       Converted Temperature 5.00°C to SByte 5.
//       Converted Temperature 5.00°C to Int16 5.
//       Converted Temperature 5.00°C to Int32 5.
//       Converted Temperature 5.00°C to Int64 5.
//       Converted Temperature 5.00°C to Byte 5.
//       Converted Temperature 5.00°C to UInt16 5.
//       Converted Temperature 5.00°C to UInt32 5.
//       Converted Temperature 5.00°C to UInt64 5.
//       Converted Temperature 5.00°C to Decimal 5.
//       Converted Temperature 5.00°C to Single 5.
//       Converted Temperature 5.00°C to Double 5.
//       Converted Temperature 5.00°C to String 5,00°C.

Comentarios

ChangeType es un método de conversión de uso general que convierte el objeto especificado por value en conversionType. El parámetro value puede ser un objeto de cualquier tipo y conversionType también puede ser un objeto Type que representa cualquier tipo base o personalizado. Para que la conversión se realice correctamente, value debe implementar la interfaz IConvertible, ya que el método simplemente ajusta una llamada a un método IConvertible adecuado. El método requiere que se admita la conversión de value a conversionType.

El parámetro provider es una implementación de IFormatProvider que proporciona información de formato para la conversión. Si se usa y cómo se usa este parámetro depende de la implementación de IConvertible subyacente. Si value es un tipo de datos base, provider solo se usa para las conversiones siguientes:

Si value es un tipo definido por la aplicación, su implementación de IConvertible puede usar el parámetro provider.

Notas a los autores de las llamadas

El método ChangeType(Object, Type, IFormatProvider) puede convertir un valor de enumeración a otro tipo. Sin embargo, no puede convertir otro tipo en un valor de enumeración, incluso si el tipo de origen es el tipo subyacente de la enumeración. Para convertir un tipo en un valor de enumeración, use un operador de conversión (en C#) o una función de conversión (en Visual Basic). En el ejemplo siguiente se muestra la conversión a y desde un valor de enumeración de Continent.

C#
using System;

public enum Continent
{
   Africa, Antarctica, Asia, Australia, Europe,
   NorthAmerica, SouthAmerica
};

public class Example
{
   public static void Main()
   {
      // Convert a Continent to a Double.
      Continent cont = Continent.NorthAmerica;
      Console.WriteLine("{0:N2}",
                        Convert.ChangeType(cont, typeof(Double)));

      // Convert a Double to a Continent.
      Double number = 6.0;
      try {
         Console.WriteLine("{0}",
                           Convert.ChangeType(number, typeof(Continent)));
      }
      catch (InvalidCastException) {
         Console.WriteLine("Cannot convert a Double to a Continent");
      }

      Console.WriteLine("{0}", (Continent) number);
   }
}
// The example displays the following output:
//       5.00
//       Cannot convert a Double to a Continent
//       SouthAmerica

El método ChangeType(Object, Type, IFormatProvider) puede convertir un tipo que acepta valores NULL a otro tipo. Sin embargo, no puede convertir otro tipo en un valor de un tipo que acepta valores NULL, incluso si conversionType es el tipo subyacente del Nullable<T>. Para realizar la conversión, puede usar un operador de conversión (en C#) o una función de conversión (en Visual Basic). En el ejemplo siguiente se muestra la conversión a y desde un tipo que acepta valores NULL.

C#
using System;

public class Example
{
   public static void Main()
   {
      int? intValue1 = 12893;
      double dValue1 = (double) Convert.ChangeType(intValue1, typeof(Double), null);
      Console.WriteLine("{0} ({1})--> {2} ({3})", intValue1, intValue1.GetType().Name,
                        dValue1, dValue1.GetType().Name);

      float fValue1 = 16.3478f;
      int? intValue2 = (int) fValue1;
      Console.WriteLine("{0} ({1})--> {2} ({3})", fValue1, fValue1.GetType().Name,
                        intValue2, intValue2.GetType().Name);
   }
}
// The example displays the following output:
//    12893 (Int32)--> 12893 (Double)
//    16.3478 (Single)--> 16 (Int32)

Se aplica a

.NET 9 y otras versiones
Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

ChangeType(Object, TypeCode, IFormatProvider)

Source:
Convert.cs
Source:
Convert.cs
Source:
Convert.cs

Devuelve un objeto del tipo especificado cuyo valor es equivalente al objeto especificado. Un parámetro proporciona información de formato específica de la referencia cultural.

C#
public static object ChangeType (object value, TypeCode typeCode, IFormatProvider provider);
C#
public static object? ChangeType (object? value, TypeCode typeCode, IFormatProvider? provider);

Parámetros

value
Object

Objeto que implementa la interfaz IConvertible.

typeCode
TypeCode

Tipo de objeto que se va a devolver.

provider
IFormatProvider

Objeto que proporciona información de formato específica de la referencia cultural.

Devoluciones

Objeto cuyo tipo subyacente es typeCode y cuyo valor es equivalente a value.

-o-

Referencia nula (Nothing en Visual Basic), si value es null y typeCode es Empty, Stringo Object.

Excepciones

Esta conversión no se admite.

-o-

value es null y typeCode especifica un tipo de valor.

-o-

value no implementa la interfaz IConvertible.

value no tiene un formato para el tipo de typeCode reconocido por provider.

value representa un número que está fuera del intervalo del tipo typeCode.

typeCode no es válido.

Ejemplos

En el ejemplo siguiente se define un proveedor de formato personalizado denominado InterceptProvider que indica cuándo se llama a su método GetFormat y devuelve un NumberFormatInfo para la referencia cultural de fr-FR y un objeto DateTimeFormatInfo para la referencia cultural de en-US. Este proveedor de formato se usa en todas las llamadas al método ChangeType(Object, TypeCode, IFormatProvider). A continuación, el ejemplo crea una matriz con un Double y un valor de DateTime y realiza llamadas repetidas a ChangeType(Object, TypeCode, IFormatProvider) con cada valor y cada miembro de la enumeración TypeCode. En el ejemplo se muestra cuándo el método usa el parámetro IFormatProvider y también muestra el uso del parámetro provider para realizar el formato que distingue la referencia cultural.

C#
using System;
using System.Globalization;

public class InterceptProvider : IFormatProvider
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(NumberFormatInfo)) {
         Console.WriteLine("   Returning a fr-FR numeric format provider.");
         return new System.Globalization.CultureInfo("fr-FR").NumberFormat;
      }
      else if (formatType == typeof(DateTimeFormatInfo)) {
         Console.WriteLine("   Returning an en-US date/time format provider.");
         return new System.Globalization.CultureInfo("en-US").DateTimeFormat;
      }
      else {
         Console.WriteLine("   Requesting a format provider of {0}.", formatType.Name);
         return null;
      }
   }
}

public class Example
{
   public static void Main()
   {
      object[] values = { 103.5d, new DateTime(2010, 12, 26, 14, 34, 0) };
      IFormatProvider provider = new InterceptProvider();

      // Convert value to each of the types represented in TypeCode enum.
      foreach (object value in values)
      {
         // Iterate types in TypeCode enum.
         foreach (TypeCode enumType in ((TypeCode[]) Enum.GetValues(typeof(TypeCode))))
         {
            if (enumType == TypeCode.DBNull || enumType == TypeCode.Empty) continue;

            try {
               Console.WriteLine("{0} ({1}) --> {2} ({3}).",
                                 value, value.GetType().Name,
                                 Convert.ChangeType(value, enumType, provider),
                                 enumType.ToString());
            }
            catch (InvalidCastException) {
               Console.WriteLine("Cannot convert a {0} to a {1}",
                                 value.GetType().Name, enumType.ToString());
            }
            catch (OverflowException) {
               Console.WriteLine("Overflow: {0} is out of the range of a {1}",
                                 value, enumType.ToString());
            }
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//    103.5 (Double) --> 103.5 (Object).
//    103.5 (Double) --> True (Boolean).
//    Cannot convert a Double to a Char
//    103.5 (Double) --> 104 (SByte).
//    103.5 (Double) --> 104 (Byte).
//    103.5 (Double) --> 104 (Int16).
//    103.5 (Double) --> 104 (UInt16).
//    103.5 (Double) --> 104 (Int32).
//    103.5 (Double) --> 104 (UInt32).
//    103.5 (Double) --> 104 (Int64).
//    103.5 (Double) --> 104 (UInt64).
//    103.5 (Double) --> 103.5 (Single).
//    103.5 (Double) --> 103.5 (Double).
//    103.5 (Double) --> 103.5 (Decimal).
//    Cannot convert a Double to a DateTime
//       Returning a fr-FR numeric format provider.
//    103.5 (Double) --> 103,5 (String).
//
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (Object).
//    Cannot convert a DateTime to a Boolean
//    Cannot convert a DateTime to a Char
//    Cannot convert a DateTime to a SByte
//    Cannot convert a DateTime to a Byte
//    Cannot convert a DateTime to a Int16
//    Cannot convert a DateTime to a UInt16
//    Cannot convert a DateTime to a Int32
//    Cannot convert a DateTime to a UInt32
//    Cannot convert a DateTime to a Int64
//    Cannot convert a DateTime to a UInt64
//    Cannot convert a DateTime to a Single
//    Cannot convert a DateTime to a Double
//    Cannot convert a DateTime to a Decimal
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (DateTime).
//       Returning an en-US date/time format provider.
//    12/26/2010 2:34:00 PM (DateTime) --> 12/26/2010 2:34:00 PM (String).

Comentarios

ChangeType(Object, TypeCode, IFormatProvider) es un método de conversión de uso general que convierte el objeto especificado por value en un tipo predefinido especificado por typeCode. El parámetro value puede ser un objeto de cualquier tipo. Para que la conversión se realice correctamente, value debe implementar la interfaz IConvertible, ya que el método simplemente ajusta una llamada a un método IConvertible adecuado. El método también requiere que se admita la conversión de value a typeCode.

El método ChangeType(Object, TypeCode, IFormatProvider) no admite la conversión de value a un tipo personalizado. Para realizar esta conversión, llame al método ChangeType(Object, Type, IFormatProvider).

El parámetro provider es una implementación de IFormatProvider que proporciona información de formato para la conversión. Si se usa y cómo se usa este parámetro depende de la implementación de IConvertible subyacente. Si value es un tipo de datos base, provider solo se usa para las conversiones siguientes. Si se pasa un argumento nullIFormatProvider a estos métodos, se usa el objeto CultureInfo que representa la referencia cultural actual.

Si value es un tipo definido por la aplicación, su implementación de IConvertible puede usar el parámetro provider.

Se aplica a

.NET 9 y otras versiones
Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0