每个值都有一个关联的类型,它定义属性,例如分配给值的空间量、它可以拥有的可能值的范围以及它提供的成员。 许多值可以表示为多个类型。 例如,值 4 可以表示为整数或浮点值。 类型转换在与旧类型的值等效的新类型中创建一个值,但不一定保留原始对象的标识(或确切值)。
.NET 自动支持以下转换:
从派生类转换为基类。 例如,这意味着任何类或结构的实例都可以转换为 Object 实例。 此转换不需要强制转换或转换运算符。
从基类转换回原始派生类。 在 C# 中,此转换需要强制转换运算符。 在 Visual Basic 中,如果
CType
处于开启状态,则需要使用运算符Option Strict
。从实现接口的类型转换为表示该接口的接口对象。 此转换不需要强制转换或转换运算符。
从接口对象转换回实现该接口的原始类型。 在 C# 中,此转换需要强制转换运算符。 在 Visual Basic 中,如果
CType
处于开启状态,则需要使用运算符Option Strict
。
除了这些自动转换之外,.NET 还提供多个支持自定义类型转换的功能。 其中包括:
运算符
Implicit
,用于定义类型之间的可用扩大转换。 有关详细信息,请参阅使用隐式运算符的隐式转换部分。运算符
Explicit
,用于定义类型之间的可用缩小转换。 有关详细信息,请参阅使用显式运算符的显式转换部分。该 IConvertible 接口定义对每个基本 .NET 数据类型的转换。 有关详细信息,请参阅 “IConvertible 接口 ”部分。
该 Convert 类提供一组方法,用于实现接口中 IConvertible 的方法。 有关详细信息,请参阅 “转换类” 部分。
该 TypeConverter 类是一个基类,可以扩展以支持将指定类型转换为任何其他类型。 有关详细信息,请参阅 TypeConverter 类 部分。
使用隐式运算符的隐式转换
扩大转换涉及从现有类型的值创建一个新值,该现有类型比目标类型具有限制性更强的范围或限制性更强的成员列表。 扩大转换不能导致数据丢失(尽管它们可能会导致精度损失)。 由于数据无法丢失,因此编译器可以隐式或透明地处理转换,而无需使用显式转换方法或强制转换运算符。
注释
尽管执行隐式转换的代码可以调用转换方法或使用强制转换运算符,但支持隐式转换的编译器不需要使用它们。
例如,该Decimal类型支持从Byte、、Char、Int16、、Int32、Int64SByte、UInt16、、 UInt32和UInt64值进行隐式转换。 以下示例说明了将值赋给 Decimal 变量时的一些隐式转换。
byte byteValue = 16;
short shortValue = -1024;
int intValue = -1034000;
long longValue = 1152921504606846976;
ulong ulongValue = UInt64.MaxValue;
decimal decimalValue;
decimalValue = byteValue;
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
byteValue.GetType().Name, decimalValue);
decimalValue = shortValue;
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
shortValue.GetType().Name, decimalValue);
decimalValue = intValue;
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
intValue.GetType().Name, decimalValue);
decimalValue = longValue;
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
longValue.GetType().Name, decimalValue);
decimalValue = ulongValue;
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
ulongValue.GetType().Name, decimalValue);
// The example displays the following output:
// After assigning a Byte value, the Decimal value is 16.
// After assigning a Int16 value, the Decimal value is -1024.
// After assigning a Int32 value, the Decimal value is -1034000.
// After assigning a Int64 value, the Decimal value is 1152921504606846976.
// After assigning a UInt64 value, the Decimal value is 18446744073709551615.
Dim byteValue As Byte = 16
Dim shortValue As Short = -1024
Dim intValue As Integer = -1034000
Dim longValue As Long = CLng(1024 ^ 6)
Dim ulongValue As ULong = ULong.MaxValue
Dim decimalValue As Decimal
decimalValue = byteValue
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
byteValue.GetType().Name, decimalValue)
decimalValue = shortValue
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
shortValue.GetType().Name, decimalValue)
decimalValue = intValue
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
intValue.GetType().Name, decimalValue)
decimalValue = longValue
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
longValue.GetType().Name, decimalValue)
decimalValue = ulongValue
Console.WriteLine("After assigning a {0} value, the Decimal value is {1}.",
ulongValue.GetType().Name, decimalValue)
' The example displays the following output:
' After assigning a Byte value, the Decimal value is 16.
' After assigning a Int16 value, the Decimal value is -1024.
' After assigning a Int32 value, the Decimal value is -1034000.
' After assigning a Int64 value, the Decimal value is 1152921504606846976.
' After assigning a UInt64 value, the Decimal value is 18446744073709551615.
如果特定语言编译器支持自定义运算符,还可以在自己的自定义类型中定义隐式转换。 以下示例提供使用符号和数量级表示形式的 ByteWithSign
已签名字节数据类型的部分实现。 它支持隐式转换 Byte 和 SByte 值到 ByteWithSign
值。
public struct ByteWithSign
{
private SByte signValue;
private Byte value;
public static implicit operator ByteWithSign(SByte value)
{
ByteWithSign newValue;
newValue.signValue = (SByte)Math.Sign(value);
newValue.value = (byte)Math.Abs(value);
return newValue;
}
public static implicit operator ByteWithSign(Byte value)
{
ByteWithSign newValue;
newValue.signValue = 1;
newValue.value = value;
return newValue;
}
public override string ToString()
{
return (signValue * value).ToString();
}
}
Public Structure ImplicitByteWithSign
Private signValue As SByte
Private value As Byte
Public Overloads Shared Widening Operator CType(value As SByte) As ImplicitByteWithSign
Dim newValue As ImplicitByteWithSign
newValue.signValue = CSByte(Math.Sign(value))
newValue.value = CByte(Math.Abs(value))
Return newValue
End Operator
Public Overloads Shared Widening Operator CType(value As Byte) As ImplicitByteWithSign
Dim NewValue As ImplicitByteWithSign
newValue.signValue = 1
newValue.value = value
Return newValue
End Operator
Public Overrides Function ToString() As String
Return (signValue * value).ToString()
End Function
End Structure
然后,客户端代码可以声明变量 ByteWithSign
并为其分配 Byte 值, SByte 而无需执行任何显式转换或使用任何强制转换运算符,如以下示例所示。
SByte sbyteValue = -120;
ByteWithSign value = sbyteValue;
Console.WriteLine(value);
value = Byte.MaxValue;
Console.WriteLine(value);
// The example displays the following output:
// -120
// 255
Dim sbyteValue As SByte = -120
Dim value As ImplicitByteWithSign = sbyteValue
Console.WriteLine(value.ToString())
value = Byte.MaxValue
Console.WriteLine(value.ToString())
' The example displays the following output:
' -120
' 255
使用显式运算符的显式转换
收缩转换涉及从现有类型的值创建一个新值,该现有类型比目标类型具有更大的范围和更大的成员列表。 由于缩小转换可能导致数据丢失,编译器通常要求通过调用转换方法或使用强制转换运算符来显式进行转换。 也就是说,必须在开发人员代码中显式处理转换。
注释
收缩转换之所以需要使用转换方法或强制转换运算符,主要是为提醒开发人员可能会丢失数据或引发 OverflowException,以便可以在代码中对其进行处理。 但是,某些编译器可以放宽此要求。 例如,在 Visual Basic 中,如果 Option Strict
处于关闭状态(其默认设置),则 Visual Basic 编译器会尝试隐式执行缩小转换。
例如,UInt32Int64和UInt64数据类型具有超出Int32该数据类型的范围,如下表所示。
类型 | 与 Int32 范围的比较 |
---|---|
Int64 | Int64.MaxValue 大于 Int32.MaxValue,小于 Int64.MinValue (负范围大于) Int32.MinValue。 |
UInt32 | UInt32.MaxValue 大于 Int32.MaxValue。 |
UInt64 | UInt64.MaxValue 大于 Int32.MaxValue。 |
为了处理此类窄转换,.NET 允许类型定义 Explicit
运算符。 然后,单个语言编译器可以使用自己的语法实现此运算符,也可以调用该类的成员 Convert 来执行转换。 (有关该 Convert 类的详细信息,请参阅本主题后面的 “转换类 ”。)下面的示例演示如何使用语言功能来处理这些可能超出范围的整数值到 Int32 值的显式转换。
long number1 = int.MaxValue + 20L;
uint number2 = int.MaxValue - 1000;
ulong number3 = int.MaxValue;
int intNumber;
try
{
intNumber = checked((int)number1);
Console.WriteLine("After assigning a {0} value, the Integer value is {1}.",
number1.GetType().Name, intNumber);
}
catch (OverflowException)
{
if (number1 > int.MaxValue)
Console.WriteLine($"Conversion failed: {number1} exceeds {int.MaxValue}.");
else
Console.WriteLine($"Conversion failed: {number1} is less than {int.MinValue}.");
}
try
{
intNumber = checked((int)number2);
Console.WriteLine("After assigning a {0} value, the Integer value is {1}.",
number2.GetType().Name, intNumber);
}
catch (OverflowException)
{
Console.WriteLine($"Conversion failed: {number2} exceeds {int.MaxValue}.");
}
try
{
intNumber = checked((int)number3);
Console.WriteLine("After assigning a {0} value, the Integer value is {1}.",
number3.GetType().Name, intNumber);
}
catch (OverflowException)
{
Console.WriteLine($"Conversion failed: {number1} exceeds {int.MaxValue}.");
}
// The example displays the following output:
// Conversion failed: 2147483667 exceeds 2147483647.
// After assigning a UInt32 value, the Integer value is 2147482647.
// After assigning a UInt64 value, the Integer value is 2147483647.
Dim number1 As Long = Integer.MaxValue + 20L
Dim number2 As UInteger = Integer.MaxValue - 1000
Dim number3 As ULong = Integer.MaxValue
Dim intNumber As Integer
Try
intNumber = CInt(number1)
Console.WriteLine("After assigning a {0} value, the Integer value is {1}.",
number1.GetType().Name, intNumber)
Catch e As OverflowException
If number1 > Integer.MaxValue Then
Console.WriteLine("Conversion failed: {0} exceeds {1}.",
number1, Integer.MaxValue)
Else
Console.WriteLine("Conversion failed: {0} is less than {1}.\n",
number1, Integer.MinValue)
End If
End Try
Try
intNumber = CInt(number2)
Console.WriteLine("After assigning a {0} value, the Integer value is {1}.",
number2.GetType().Name, intNumber)
Catch e As OverflowException
Console.WriteLine("Conversion failed: {0} exceeds {1}.",
number2, Integer.MaxValue)
End Try
Try
intNumber = CInt(number3)
Console.WriteLine("After assigning a {0} value, the Integer value is {1}.",
number3.GetType().Name, intNumber)
Catch e As OverflowException
Console.WriteLine("Conversion failed: {0} exceeds {1}.",
number1, Integer.MaxValue)
End Try
' The example displays the following output:
' Conversion failed: 2147483667 exceeds 2147483647.
' After assigning a UInt32 value, the Integer value is 2147482647.
' After assigning a UInt64 value, the Integer value is 2147483647.
显式转换可以生成不同语言的不同结果,这些结果可能与相应 Convert 方法返回的值不同。 例如,如果将 Double 值 12.63251 转换为 Int32,则 Visual Basic CInt
方法和 .NET Convert.ToInt32(Double) 方法会对 Double 进行舍入以返回值 13,而 C# (int)
运算符会截断 Double 以返回值 12。 同样,C# (int)
运算符不支持布尔到整数转换,但 Visual Basic CInt
方法将值 true
转换为 -1。 另一方面,该方法 Convert.ToInt32(Boolean) 将值 true
转换为 1。
大多数编译器允许以选中或未选中的方式执行显式转换。 当执行有检查转换时,如果被转换类型的值超出了目标类型的范围,则会引发 OverflowException。 当在同一条件下执行未检查的转换时,转换可能不会引发异常,但确切的行为变得未定义,并且可能会生成不正确的值。
注释
在 C# 中,可以使用 checked
关键字与强制转换运算符相结合,或通过指定 /checked+
编译器选项,来执行检查性转换。 反过来,可将 unchecked
关键字与强制转换运算符一起使用来执行无检查转换,或者通过指定 /checked-
编译器选项来执行无检查转换。 默认情况下,显式转换将为无检查转换。 在 Visual Basic 中,可以通过取消选中项目高级编译器设置对话框中的“删除整数溢出检查”复选框,或指定/removeintchecks-
编译器选项来执行检查转换。 相反,可以通过在项目的“高级编译器设置”对话框中选中“删除整数溢出检查”复选框或指定编译器选项来执行未选中的/removeintchecks+
转换。 默认情况下,显式转换将为有检查转换。
下面的 C# 示例使用 checked
和 unchecked
关键字来说明当值超出范围 Byte 的值转换为 a Byte时的行为差异。 检查的转换会引发异常,但未检查的转换将Byte.MaxValue分配给Byte变量。
int largeValue = Int32.MaxValue;
byte newValue;
try
{
newValue = unchecked((byte)largeValue);
Console.WriteLine($"Converted the {largeValue.GetType().Name} value {largeValue} to the {newValue.GetType().Name} value {newValue}.");
}
catch (OverflowException)
{
Console.WriteLine($"{largeValue} is outside the range of the Byte data type.");
}
try
{
newValue = checked((byte)largeValue);
Console.WriteLine($"Converted the {largeValue.GetType().Name} value {largeValue} to the {newValue.GetType().Name} value {newValue}.");
}
catch (OverflowException)
{
Console.WriteLine($"{largeValue} is outside the range of the Byte data type.");
}
// The example displays the following output:
// Converted the Int32 value 2147483647 to the Byte value 255.
// 2147483647 is outside the range of the Byte data type.
如果特定语言编译器支持自定义重载运算符,还可以在自己的自定义类型中定义显式转换。 以下示例提供使用符号和数量级表示形式的 ByteWithSign
已签名字节数据类型的部分实现。 它支持将Int32值和UInt32值显式转换为ByteWithSign
值。
public struct ByteWithSignE
{
private SByte signValue;
private Byte value;
private const byte MaxValue = byte.MaxValue;
private const int MinValue = -1 * byte.MaxValue;
public static explicit operator ByteWithSignE(int value)
{
// Check for overflow.
if (value > ByteWithSignE.MaxValue || value < ByteWithSignE.MinValue)
throw new OverflowException(String.Format("'{0}' is out of range of the ByteWithSignE data type.",
value));
ByteWithSignE newValue;
newValue.signValue = (SByte)Math.Sign(value);
newValue.value = (byte)Math.Abs(value);
return newValue;
}
public static explicit operator ByteWithSignE(uint value)
{
if (value > ByteWithSignE.MaxValue)
throw new OverflowException(String.Format("'{0}' is out of range of the ByteWithSignE data type.",
value));
ByteWithSignE newValue;
newValue.signValue = 1;
newValue.value = (byte)value;
return newValue;
}
public override string ToString()
{
return (signValue * value).ToString();
}
}
Public Structure ByteWithSign
Private signValue As SByte
Private value As Byte
Private Const MaxValue As Byte = Byte.MaxValue
Private Const MinValue As Integer = -1 * Byte.MaxValue
Public Overloads Shared Narrowing Operator CType(value As Integer) As ByteWithSign
' Check for overflow.
If value > ByteWithSign.MaxValue Or value < ByteWithSign.MinValue Then
Throw New OverflowException(String.Format("'{0}' is out of range of the ByteWithSign data type.", value))
End If
Dim newValue As ByteWithSign
newValue.signValue = CSByte(Math.Sign(value))
newValue.value = CByte(Math.Abs(value))
Return newValue
End Operator
Public Overloads Shared Narrowing Operator CType(value As UInteger) As ByteWithSign
If value > ByteWithSign.MaxValue Then
Throw New OverflowException(String.Format("'{0}' is out of range of the ByteWithSign data type.", value))
End If
Dim NewValue As ByteWithSign
newValue.signValue = 1
newValue.value = CByte(value)
Return newValue
End Operator
Public Overrides Function ToString() As String
Return (signValue * value).ToString()
End Function
End Structure
然后,客户端代码可以声明变量 ByteWithSign
,并在赋值包括强制转换运算符或转换方法时分配变量 Int32 和 UInt32 值,如以下示例所示。
ByteWithSignE value;
try
{
int intValue = -120;
value = (ByteWithSignE)intValue;
Console.WriteLine(value);
}
catch (OverflowException e)
{
Console.WriteLine(e.Message);
}
try
{
uint uintValue = 1024;
value = (ByteWithSignE)uintValue;
Console.WriteLine(value);
}
catch (OverflowException e)
{
Console.WriteLine(e.Message);
}
// The example displays the following output:
// -120
// '1024' is out of range of the ByteWithSignE data type.
Dim value As ByteWithSign
Try
Dim intValue As Integer = -120
value = CType(intValue, ByteWithSign)
Console.WriteLine(value)
Catch e As OverflowException
Console.WriteLine(e.Message)
End Try
Try
Dim uintValue As UInteger = 1024
value = CType(uintValue, ByteWithSign)
Console.WriteLine(value)
Catch e As OverflowException
Console.WriteLine(e.Message)
End Try
' The example displays the following output:
' -120
' '1024' is out of range of the ByteWithSign data type.
IConvertible 接口
为了支持将任何类型的转换为公共语言运行时基类型,.NET 提供 IConvertible 接口。 实现类型需要提供以下内容:
一个返回实现类型的 TypeCode 的方法。
将实现类型转换为每个公共语言运行时基类型(Boolean、、Byte、DateTimeDecimal、、Double等)的方法。
通用转换方法,用于将实现类型的实例转换为另一个指定类型。 不支持的转换应引发 InvalidCastException。
每个公共语言运行时基类型(即,Boolean、Byte、Char、DateTime、Decimal、Double、Int16、Int32、Int64、SByte、Single、String、UInt16、UInt32、UInt64),以及DBNull和Enum类型,都实现了IConvertible接口。 但是,这些是显式接口实现;转换方法只能通过 IConvertible 接口变量调用,如以下示例所示。 此示例将值 Int32 转换为其等效 Char 值。
int codePoint = 1067;
IConvertible iConv = codePoint;
char ch = iConv.ToChar(null);
Console.WriteLine($"Converted {codePoint} to {ch}.");
Dim codePoint As Integer = 1067
Dim iConv As IConvertible = codePoint
Dim ch As Char = iConv.ToChar(Nothing)
Console.WriteLine("Converted {0} to {1}.", codePoint, ch)
在接口上调用转换方法的要求,而不是在实现类型上调用转换方法的要求使得显式接口实现相对昂贵。 相反,我们建议调用类的 Convert 相应成员,以在公共语言运行时基类型之间进行转换。 有关详细信息,请参阅下一部分“ 转换类”。
注释
除了 IConvertible .NET 提供的接口和 Convert 类外,各个语言还可以提供执行转换的方法。 例如,C# 使用强制转换运算符;Visual Basic 使用编译器实现的转换函数,例如 CType
, CInt
和 DirectCast
。
在大多数情况下,该 IConvertible 接口旨在支持在 .NET 中基类型之间进行转换。 但是,接口也可以由自定义类型实现,以支持将该类型转换为其他自定义类型。 有关详细信息,请参阅本主题后面的 ChangeType 方法的自定义转换 部分。
Convert 类
尽管可以通过调用每个基类型的 IConvertible 接口实现来执行类型转换,但建议使用调用类 System.Convert 的方法,这是与语言无关的方法,从一种基类型转换为另一种基类型。 此外, Convert.ChangeType(Object, Type, IFormatProvider) 该方法还可用于从指定的自定义类型转换为另一种类型。
基类型之间的转换
该 Convert 类提供了一种非特定语言的方法,用于在基类型之间执行转换,并且可用于面向公共语言运行时的所有语言。 它提供了一整套用于扩大和缩小转换的完整方法,并在不支持的转换(例如将InvalidCastException值转换为整数值)时抛出DateTime。 收缩转换是在已检查的上下文中执行的,如果转换失败,将引发 OverflowException。
重要
由于该 Convert 类包含用于转换到每个基类型的方法以及从每个基类型转换的方法,因此无需调用每个基类型的 IConvertible 显式接口实现。
下面的示例演示如何使用 System.Convert 类在 .NET 基类型之间执行多个扩大和缩小转换。
// Convert an Int32 value to a Decimal (a widening conversion).
int integralValue = 12534;
decimal decimalValue = Convert.ToDecimal(integralValue);
Console.WriteLine($"Converted the {integralValue.GetType().Name} value {integralValue} to " +
"the {decimalValue.GetType().Name} value {decimalValue:N2}.");
// Convert a Byte value to an Int32 value (a widening conversion).
byte byteValue = Byte.MaxValue;
int integralValue2 = Convert.ToInt32(byteValue);
Console.WriteLine($"Converted the {byteValue.GetType().Name} value {byteValue} to " +
"the {integralValue2.GetType().Name} value {integralValue2:G}.");
// Convert a Double value to an Int32 value (a narrowing conversion).
double doubleValue = 16.32513e12;
try
{
long longValue = Convert.ToInt64(doubleValue);
Console.WriteLine($"Converted the {doubleValue.GetType().Name} value {doubleValue:E} to " +
"the {longValue.GetType().Name} value {longValue:N0}.");
}
catch (OverflowException)
{
Console.WriteLine($"Unable to convert the {doubleValue.GetType().Name:E} value {doubleValue}.");
}
// Convert a signed byte to a byte (a narrowing conversion).
sbyte sbyteValue = -16;
try
{
byte byteValue2 = Convert.ToByte(sbyteValue);
Console.WriteLine($"Converted the {sbyteValue.GetType().Name} value {sbyteValue} to " +
"the {byteValue2.GetType().Name} value {byteValue2:G}.");
}
catch (OverflowException)
{
Console.WriteLine($"Unable to convert the {sbyteValue.GetType().Name} value {sbyteValue}.");
}
// The example displays the following output:
// Converted the Int32 value 12534 to the Decimal value 12,534.00.
// Converted the Byte value 255 to the Int32 value 255.
// Converted the Double value 1.632513E+013 to the Int64 value 16,325,130,000,000.
// Unable to convert the SByte value -16.
' Convert an Int32 value to a Decimal (a widening conversion).
Dim integralValue As Integer = 12534
Dim decimalValue As Decimal = Convert.ToDecimal(integralValue)
Console.WriteLine("Converted the {0} value {1} to the {2} value {3:N2}.",
integralValue.GetType().Name,
integralValue,
decimalValue.GetType().Name,
decimalValue)
' Convert a Byte value to an Int32 value (a widening conversion).
Dim byteValue As Byte = Byte.MaxValue
Dim integralValue2 As Integer = Convert.ToInt32(byteValue)
Console.WriteLine("Converted the {0} value {1} to " +
"the {2} value {3:G}.",
byteValue.GetType().Name,
byteValue,
integralValue2.GetType().Name,
integralValue2)
' Convert a Double value to an Int32 value (a narrowing conversion).
Dim doubleValue As Double = 16.32513e12
Try
Dim longValue As Long = Convert.ToInt64(doubleValue)
Console.WriteLine("Converted the {0} value {1:E} to " +
"the {2} value {3:N0}.",
doubleValue.GetType().Name,
doubleValue,
longValue.GetType().Name,
longValue)
Catch e As OverflowException
Console.WriteLine("Unable to convert the {0:E} value {1}.",
doubleValue.GetType().Name, doubleValue)
End Try
' Convert a signed byte to a byte (a narrowing conversion).
Dim sbyteValue As SByte = -16
Try
Dim byteValue2 As Byte = Convert.ToByte(sbyteValue)
Console.WriteLine("Converted the {0} value {1} to " +
"the {2} value {3:G}.",
sbyteValue.GetType().Name,
sbyteValue,
byteValue2.GetType().Name,
byteValue2)
Catch e As OverflowException
Console.WriteLine("Unable to convert the {0} value {1}.",
sbyteValue.GetType().Name, sbyteValue)
End Try
' The example displays the following output:
' Converted the Int32 value 12534 to the Decimal value 12,534.00.
' Converted the Byte value 255 to the Int32 value 255.
' Converted the Double value 1.632513E+013 to the Int64 value 16,325,130,000,000.
' Unable to convert the SByte value -16.
在某些情况下,尤其是在进行浮点值之间的转换时,即使它不抛出OverflowException,转换也可能导致精度丢失。 下面的示例演示了这种精度损失。 在第一种情况下, Decimal 当值转换为 a Double时,精度较低(有效位数更少)。 在第二种情况下,Double 值从 42.72 四舍五入为 43 以完成转换。
double doubleValue;
// Convert a Double to a Decimal.
decimal decimalValue = 13956810.96702888123451471211m;
doubleValue = Convert.ToDouble(decimalValue);
Console.WriteLine($"{decimalValue} converted to {doubleValue}.");
doubleValue = 42.72;
try
{
int integerValue = Convert.ToInt32(doubleValue);
Console.WriteLine($"{doubleValue} converted to {integerValue}.");
}
catch (OverflowException)
{
Console.WriteLine($"Unable to convert {doubleValue} to an integer.");
}
// The example displays the following output:
// 13956810.96702888123451471211 converted to 13956810.9670289.
// 42.72 converted to 43.
Dim doubleValue As Double
' Convert a Double to a Decimal.
Dim decimalValue As Decimal = 13956810.96702888123451471211d
doubleValue = Convert.ToDouble(decimalValue)
Console.WriteLine("{0} converted to {1}.", decimalValue, doubleValue)
doubleValue = 42.72
Try
Dim integerValue As Integer = Convert.ToInt32(doubleValue)
Console.WriteLine("{0} converted to {1}.",
doubleValue, integerValue)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to an integer.",
doubleValue)
End Try
' The example displays the following output:
' 13956810.96702888123451471211 converted to 13956810.9670289.
' 42.72 converted to 43.
要查看列出了 Convert 类支持的扩大和缩小转换的表,请参阅 类型转换表。
使用 ChangeType 方法进行自定义转换
除了支持转换到每个基类型之外,该 Convert 类还可用于将自定义类型转换为一个或多个预定义类型。 此转换是通过 Convert.ChangeType(Object, Type, IFormatProvider) 方法执行的,而此方法包装了对 IConvertible.ToType 参数的 value
方法的调用。 这意味着由参数 value
表示的对象必须提供对接口 IConvertible 的实现。
注释
Convert.ChangeType(Object, Type)由于和Convert.ChangeType(Object, Type, IFormatProvider)方法使用Type对象来指定要转换的目标类型value
,因此它们可用于对在编译时未知类型的对象执行动态转换。 但是,请注意,IConvertible 的 value
实现仍必须支持此转换。
下面的示例演示了接口的可能实现 IConvertible ,该接口允许 TemperatureCelsius
对象转换为 TemperatureFahrenheit
对象,反之亦然。 该示例定义了一个基类Temperature
,它实现了IConvertible接口并重写了Object.ToString方法。 派生类 TemperatureCelsius
和 TemperatureFahrenheit
均重写了基类的 ToType
方法和 ToString
方法。
using System;
public abstract class Temperature : IConvertible
{
protected decimal temp;
public Temperature(decimal temperature)
{
this.temp = temperature;
}
public decimal Value
{
get { return this.temp; }
set { this.temp = value; }
}
public override string ToString()
{
return temp.ToString(null as IFormatProvider) + "º";
}
// IConvertible implementations.
public TypeCode GetTypeCode()
{
return TypeCode.Object;
}
public bool ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException(String.Format("Temperature-to-Boolean conversion is not supported."));
}
public byte ToByte(IFormatProvider provider)
{
if (temp < Byte.MinValue || temp > Byte.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the Byte data type.", temp));
else
return (byte)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 temp;
}
public double ToDouble(IFormatProvider provider)
{
return (double)temp;
}
public short ToInt16(IFormatProvider provider)
{
if (temp < Int16.MinValue || temp > Int16.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the Int16 data type.", temp));
else
return (short)Math.Round(temp);
}
public int ToInt32(IFormatProvider provider)
{
if (temp < Int32.MinValue || temp > Int32.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the Int32 data type.", temp));
else
return (int)Math.Round(temp);
}
public long ToInt64(IFormatProvider provider)
{
if (temp < Int64.MinValue || temp > Int64.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the Int64 data type.", temp));
else
return (long)Math.Round(temp);
}
public sbyte ToSByte(IFormatProvider provider)
{
if (temp < SByte.MinValue || temp > SByte.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the SByte data type.", temp));
else
return (sbyte)temp;
}
public float ToSingle(IFormatProvider provider)
{
return (float)temp;
}
public virtual string ToString(IFormatProvider provider)
{
return temp.ToString(provider) + "°";
}
// If conversionType is implemented by another IConvertible method, call it.
public virtual object ToType(Type conversionType, IFormatProvider provider)
{
switch (Type.GetTypeCode(conversionType))
{
case TypeCode.Boolean:
return this.ToBoolean(provider);
case TypeCode.Byte:
return this.ToByte(provider);
case TypeCode.Char:
return this.ToChar(provider);
case TypeCode.DateTime:
return this.ToDateTime(provider);
case TypeCode.Decimal:
return this.ToDecimal(provider);
case TypeCode.Double:
return this.ToDouble(provider);
case TypeCode.Empty:
throw new NullReferenceException("The target type is null.");
case TypeCode.Int16:
return this.ToInt16(provider);
case TypeCode.Int32:
return this.ToInt32(provider);
case TypeCode.Int64:
return this.ToInt64(provider);
case TypeCode.Object:
// Leave conversion of non-base types to derived classes.
throw new InvalidCastException(String.Format("Cannot convert from Temperature to {0}.",
conversionType.Name));
case TypeCode.SByte:
return this.ToSByte(provider);
case TypeCode.Single:
return this.ToSingle(provider);
case TypeCode.String:
IConvertible iconv = this;
return iconv.ToString(provider);
case TypeCode.UInt16:
return this.ToUInt16(provider);
case TypeCode.UInt32:
return this.ToUInt32(provider);
case TypeCode.UInt64:
return this.ToUInt64(provider);
default:
throw new InvalidCastException("Conversion not supported.");
}
}
public ushort ToUInt16(IFormatProvider provider)
{
if (temp < UInt16.MinValue || temp > UInt16.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the UInt16 data type.", temp));
else
return (ushort)Math.Round(temp);
}
public uint ToUInt32(IFormatProvider provider)
{
if (temp < UInt32.MinValue || temp > UInt32.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the UInt32 data type.", temp));
else
return (uint)Math.Round(temp);
}
public ulong ToUInt64(IFormatProvider provider)
{
if (temp < UInt64.MinValue || temp > UInt64.MaxValue)
throw new OverflowException(String.Format("{0} is out of range of the UInt64 data type.", temp));
else
return (ulong)Math.Round(temp);
}
}
public class TemperatureCelsius : Temperature, IConvertible
{
public TemperatureCelsius(decimal value) : base(value)
{
}
// Override ToString methods.
public override string ToString()
{
return this.ToString(null);
}
public override string ToString(IFormatProvider provider)
{
return temp.ToString(provider) + "°C";
}
// If conversionType is a implemented by another IConvertible method, call it.
public override object ToType(Type conversionType, IFormatProvider provider)
{
// For non-objects, call base method.
if (Type.GetTypeCode(conversionType) != TypeCode.Object)
{
return base.ToType(conversionType, provider);
}
else
{
if (conversionType.Equals(typeof(TemperatureCelsius)))
return this;
else if (conversionType.Equals(typeof(TemperatureFahrenheit)))
return new TemperatureFahrenheit((decimal)this.temp * 9 / 5 + 32);
else
throw new InvalidCastException(String.Format("Cannot convert from Temperature to {0}.",
conversionType.Name));
}
}
}
public class TemperatureFahrenheit : Temperature, IConvertible
{
public TemperatureFahrenheit(decimal value) : base(value)
{
}
// Override ToString methods.
public override string ToString()
{
return this.ToString(null);
}
public override string ToString(IFormatProvider provider)
{
return temp.ToString(provider) + "°F";
}
public override object ToType(Type conversionType, IFormatProvider provider)
{
// For non-objects, call base method.
if (Type.GetTypeCode(conversionType) != TypeCode.Object)
{
return base.ToType(conversionType, provider);
}
else
{
// Handle conversion between derived classes.
if (conversionType.Equals(typeof(TemperatureFahrenheit)))
return this;
else if (conversionType.Equals(typeof(TemperatureCelsius)))
return new TemperatureCelsius((decimal)(this.temp - 32) * 5 / 9);
// Unspecified object type: throw an InvalidCastException.
else
throw new InvalidCastException(String.Format("Cannot convert from Temperature to {0}.",
conversionType.Name));
}
}
}
Public MustInherit Class Temperature
Implements IConvertible
Protected temp As Decimal
Public Sub New(temperature As Decimal)
Me.temp = temperature
End Sub
Public Property Value As Decimal
Get
Return Me.temp
End Get
Set
Me.temp = Value
End Set
End Property
Public Overrides Function ToString() As String
Return temp.ToString() & "º"
End Function
' IConvertible implementations.
Public Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode
Return TypeCode.Object
End Function
Public Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean
Throw New InvalidCastException(String.Format("Temperature-to-Boolean conversion is not supported."))
End Function
Public Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte
If temp < Byte.MinValue Or temp > Byte.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the Byte data type.", temp))
Else
Return CByte(temp)
End If
End Function
Public Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar
Throw New InvalidCastException("Temperature-to-Char conversion is not supported.")
End Function
Public Function ToDateTime(provider As IFormatProvider) As DateTime Implements IConvertible.ToDateTime
Throw New InvalidCastException("Temperature-to-DateTime conversion is not supported.")
End Function
Public Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal
Return temp
End Function
Public Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble
Return CDbl(temp)
End Function
Public Function ToInt16(provider As IFormatProvider) As Int16 Implements IConvertible.ToInt16
If temp < Int16.MinValue Or temp > Int16.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the Int16 data type.", temp))
End If
Return CShort(Math.Round(temp))
End Function
Public Function ToInt32(provider As IFormatProvider) As Int32 Implements IConvertible.ToInt32
If temp < Int32.MinValue Or temp > Int32.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the Int32 data type.", temp))
End If
Return CInt(Math.Round(temp))
End Function
Public Function ToInt64(provider As IFormatProvider) As Int64 Implements IConvertible.ToInt64
If temp < Int64.MinValue Or temp > Int64.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the Int64 data type.", temp))
End If
Return CLng(Math.Round(temp))
End Function
Public Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte
If temp < SByte.MinValue Or temp > SByte.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the SByte data type.", temp))
Else
Return CSByte(temp)
End If
End Function
Public Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle
Return CSng(temp)
End Function
Public Overridable Overloads Function ToString(provider As IFormatProvider) As String Implements IConvertible.ToString
Return temp.ToString(provider) & " °C"
End Function
' If conversionType is a implemented by another IConvertible method, call it.
Public Overridable Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType
Select Case Type.GetTypeCode(conversionType)
Case TypeCode.Boolean
Return Me.ToBoolean(provider)
Case TypeCode.Byte
Return Me.ToByte(provider)
Case TypeCode.Char
Return Me.ToChar(provider)
Case TypeCode.DateTime
Return Me.ToDateTime(provider)
Case TypeCode.Decimal
Return Me.ToDecimal(provider)
Case TypeCode.Double
Return Me.ToDouble(provider)
Case TypeCode.Empty
Throw New NullReferenceException("The target type is null.")
Case TypeCode.Int16
Return Me.ToInt16(provider)
Case TypeCode.Int32
Return Me.ToInt32(provider)
Case TypeCode.Int64
Return Me.ToInt64(provider)
Case TypeCode.Object
' Leave conversion of non-base types to derived classes.
Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _
conversionType.Name))
Case TypeCode.SByte
Return Me.ToSByte(provider)
Case TypeCode.Single
Return Me.ToSingle(provider)
Case TypeCode.String
Return Me.ToString(provider)
Case TypeCode.UInt16
Return Me.ToUInt16(provider)
Case TypeCode.UInt32
Return Me.ToUInt32(provider)
Case TypeCode.UInt64
Return Me.ToUInt64(provider)
Case Else
Throw New InvalidCastException("Conversion not supported.")
End Select
End Function
Public Function ToUInt16(provider As IFormatProvider) As UInt16 Implements IConvertible.ToUInt16
If temp < UInt16.MinValue Or temp > UInt16.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the UInt16 data type.", temp))
End If
Return CUShort(Math.Round(temp))
End Function
Public Function ToUInt32(provider As IFormatProvider) As UInt32 Implements IConvertible.ToUInt32
If temp < UInt32.MinValue Or temp > UInt32.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the UInt32 data type.", temp))
End If
Return CUInt(Math.Round(temp))
End Function
Public Function ToUInt64(provider As IFormatProvider) As UInt64 Implements IConvertible.ToUInt64
If temp < UInt64.MinValue Or temp > UInt64.MaxValue Then
Throw New OverflowException(String.Format("{0} is out of range of the UInt64 data type.", temp))
End If
Return CULng(Math.Round(temp))
End Function
End Class
Public Class TemperatureCelsius : Inherits Temperature : Implements IConvertible
Public Sub New(value As Decimal)
MyBase.New(value)
End Sub
' Override ToString methods.
Public Overrides Function ToString() As String
Return Me.ToString(Nothing)
End Function
Public Overrides Function ToString(provider As IFormatProvider) As String
Return temp.ToString(provider) + "°C"
End Function
' If conversionType is a implemented by another IConvertible method, call it.
Public Overrides Function ToType(conversionType As Type, provider As IFormatProvider) As Object
' For non-objects, call base method.
If Type.GetTypeCode(conversionType) <> TypeCode.Object Then
Return MyBase.ToType(conversionType, provider)
Else
If conversionType.Equals(GetType(TemperatureCelsius)) Then
Return Me
ElseIf conversionType.Equals(GetType(TemperatureFahrenheit))
Return New TemperatureFahrenheit(CDec(Me.temp * 9 / 5 + 32))
' Unspecified object type: throw an InvalidCastException.
Else
Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _
conversionType.Name))
End If
End If
End Function
End Class
Public Class TemperatureFahrenheit : Inherits Temperature : Implements IConvertible
Public Sub New(value As Decimal)
MyBase.New(value)
End Sub
' Override ToString methods.
Public Overrides Function ToString() As String
Return Me.ToString(Nothing)
End Function
Public Overrides Function ToString(provider As IFormatProvider) As String
Return temp.ToString(provider) + "°F"
End Function
Public Overrides Function ToType(conversionType As Type, provider As IFormatProvider) As Object
' For non-objects, call base method.
If Type.GetTypeCode(conversionType) <> TypeCode.Object Then
Return MyBase.ToType(conversionType, provider)
Else
' Handle conversion between derived classes.
If conversionType.Equals(GetType(TemperatureFahrenheit)) Then
Return Me
ElseIf conversionType.Equals(GetType(TemperatureCelsius))
Return New TemperatureCelsius(CDec((MyBase.temp - 32) * 5 / 9))
' Unspecified object type: throw an InvalidCastException.
Else
Throw New InvalidCastException(String.Format("Cannot convert from Temperature to {0}.", _
conversionType.Name))
End If
End If
End Function
End Class
下面的示例演示了对这些IConvertible实现的多个调用,以将对象转换为TemperatureCelsius
TemperatureFahrenheit
对象,反之亦然。
TemperatureCelsius tempC1 = new TemperatureCelsius(0);
TemperatureFahrenheit tempF1 = (TemperatureFahrenheit)Convert.ChangeType(tempC1, typeof(TemperatureFahrenheit), null);
Console.WriteLine($"{tempC1} equals {tempF1}.");
TemperatureCelsius tempC2 = (TemperatureCelsius)Convert.ChangeType(tempC1, typeof(TemperatureCelsius), null);
Console.WriteLine($"{tempC1} equals {tempC2}.");
TemperatureFahrenheit tempF2 = new TemperatureFahrenheit(212);
TemperatureCelsius tempC3 = (TemperatureCelsius)Convert.ChangeType(tempF2, typeof(TemperatureCelsius), null);
Console.WriteLine($"{tempF2} equals {tempC3}.");
TemperatureFahrenheit tempF3 = (TemperatureFahrenheit)Convert.ChangeType(tempF2, typeof(TemperatureFahrenheit), null);
Console.WriteLine($"{tempF2} equals {tempF3}.");
// The example displays the following output:
// 0°C equals 32°F.
// 0°C equals 0°C.
// 212°F equals 100°C.
// 212°F equals 212°F.
Dim tempC1 As New TemperatureCelsius(0)
Dim tempF1 As TemperatureFahrenheit = CType(Convert.ChangeType(tempC1, GetType(TemperatureFahrenheit), Nothing), TemperatureFahrenheit)
Console.WriteLine("{0} equals {1}.", tempC1, tempF1)
Dim tempC2 As TemperatureCelsius = CType(Convert.ChangeType(tempC1, GetType(TemperatureCelsius), Nothing), TemperatureCelsius)
Console.WriteLine("{0} equals {1}.", tempC1, tempC2)
Dim tempF2 As New TemperatureFahrenheit(212)
Dim tempC3 As TEmperatureCelsius = CType(Convert.ChangeType(tempF2, GEtType(TemperatureCelsius), Nothing), TemperatureCelsius)
Console.WriteLine("{0} equals {1}.", tempF2, tempC3)
Dim tempF3 As TemperatureFahrenheit = CType(Convert.ChangeType(tempF2, GetType(TemperatureFahrenheit), Nothing), TemperatureFahrenheit)
Console.WriteLine("{0} equals {1}.", tempF2, tempF3)
' The example displays the following output:
' 0°C equals 32°F.
' 0°C equals 0°C.
' 212°F equals 100°C.
' 212°F equals 212°F.
TypeConverter 类
.NET 还允许您通过扩展 System.ComponentModel.TypeConverter 类来定义一个自定义类型的类型转换器,并通过 System.ComponentModel.TypeConverterAttribute 属性将类型转换器与该类型关联。 下表重点介绍了此方法与实现 IConvertible 自定义类型的接口之间的差异。
注释
仅当为其定义了类型转换器时,才能为自定义类型提供设计时支持。
使用 TypeConverter 进行转换 | 使用 IConvertible 转换 |
---|---|
通过从 TypeConverter中派生单独的类来实现自定义类型。 此派生类通过应用 TypeConverterAttribute 属性与自定义类型相关联。 | 由自定义类型实现,以执行转换。 该类型的用户必须对该类型调用 IConvertible 转换方法。 |
可以在设计时和运行时使用。 | 只能在运行时使用。 |
使用反射,因此,速度比通过 IConvertible 启用的转换要慢。 | 不使用反射。 |
允许将双向类型从自定义类型转换为其他数据类型,以及从其他数据类型转换为自定义类型。 例如,为TypeConverter定义的MyType 允许从MyType 转换到String,以及从String转换到MyType 。 |
允许从自定义类型转换为其他数据类型,但不允许从其他数据类型转换为自定义类型。 |
有关使用类型转换器执行转换的详细信息,请参阅 System.ComponentModel.TypeConverter。