显式转换

更新:2007 年 11 月

显式转换是特定于语言的转换执行方法。有些编译器需要显式转换来支持收缩转换。

虽然大多数针对公共语言运行时的语言都支持显式转换,但实际的机制却因语言而异。某些面向公共语言运行时的语言可能要求显式执行特定的转换;而其他语言则可能允许隐式执行同样的转换。同样,某些语言在某些情况下可能需要显式执行特定转换(例如在 Visual Basic 中将 Option Strict 设置为 on 的情况),但在另一些情况下将隐式执行转换(例如在 Visual Basic 中将 Option Strict 设置为 off 的情况)。请参见您所用语言的文档,以了解有关显式转换的更多信息。

在某些语言(如 C# 和 C++)中,显式转换是使用强制转换执行的。使用定义要执行的转换类型的数据类型作为转换的前缀时,发生强制转换。在 Visual Basic 等其他语言中,显式转换是通过调用转换函数执行的。在 Visual Basic 中,CType 函数或者某个特定类型转换函数(如 CStr 或 CInt)用于允许显式转换不允许进行隐式转换的数据类型。

大多数编译器允许以有检查或无检查的方式执行显式转换。当执行有检查转换时,如果被转换类型的值超出了目标类型的范围,则会引发 OverflowException。在相同情况下执行无检查转换时,转换的值可能不会导致引发异常,但实际的行为会变得不明确,并且可能产生不正确的值。

说明:

在 C# 中,可将 checked 关键字与强制转换运算符一起使用来执行有检查转换,也可通过指定 /checked+ 编译器选项来执行有检查转换。反过来,可将 unchecked 关键字与强制转换运算符一起使用来执行无检查转换,或者通过指定 /checked- 编译器选项来执行无检查转换。默认情况下,显式转换将为无检查转换。在 Visual Basic 中,通过清除项目的“高级编译器设置”对话框中的“不做整数溢出检查”复选框或指定 /removeintchecks- 编译器选项,可以执行有检查转换。反之,通过选中项目的“高级编译器设置”对话框中的“不做整数溢出检查”复选框,或者指定 /removeintchecks+ 编译器选项,可以执行无检查转换。默认情况下,显式转换将为有检查转换。

下面示例演示了一个无检查的 C# 强制转换,它尝试将 Int32.MaxValue 转换为 Byte 值。请注意,虽然整数值超出了目标 Byte 数据类型的范围,但是转换不会引发 OverflowException

// The integer value is set to 2147483647.
int myInt = int.MaxValue;
try
{
   byte myByte = (byte)myInt;
   Console.WriteLine("The byte value is {0}.", myByte);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert {0} to a byte.", myInt);
}   
// The value of MyByte is 255, the maximum value of a Byte.
// No overflow exception is thrown.

下面的示例演示了使用 Visual Basic 中的有检查 CByte 函数的显式转换,以及在 C# 中使用 checked 关键字的有检查强制转换的显式转换。此示例尝试将 Int32.MaxValue 转换为 Byte 值。但是,因为 Int32.MaxValue 超出了 Byte 数据类型的范围,所以引发了 OverflowException

' The integer value is set to 2147483647.
Dim myInt As Integer = Integer.MaxValue
Try
   Dim myByte As Byte = CByte(myInt)
   Console.WriteLine("The byte value is {0}.", myByte)
Catch e As OverflowException
   Console.WriteLine("Unable to convert {0} to a byte.", myInt)
End Try   
' Attempting to convert Int32.MaxValue to a Byte 
' throws an OverflowException.
// The integer value is set to 2147483647.
int myInt = int.MaxValue;
try
{
   byte myByte = checked ((byte) myInt);
   Console.WriteLine("The byte value is {0}.", myByte);
}
catch (OverflowException)
{
   Console.WriteLine("Unable to convert {0} to a byte.", myInt);
}   
// Attempting to convert Int32.MaxValue to a Byte 
// throws an OverflowException.

请注意,显式转换在不同的语言中可能产生不同的结果,并且这些结果可能因对应的 Convert 方法的行为而异。有关显式转换行为的信息,请参见所用语言的文档。例如,在 Visual Basic 中使用 CInt 函数将 Double 值转换为 Int32 值时,将执行四舍五入。但是,使用显式转换在 C# 中执行同一转换时,小数点右边的值将丢失。下面的代码示例使用显式转换将一个双精度值转换为一个整数值。

Dim myDouble As Double = 42.72
Dim myInt As Integer = CInt(myDouble)
Console.WriteLine(myInt)
' myInt has a value of 43.
Double myDouble = 42.72;
int myInt = checked ((int)myDouble);
Console.WriteLine(myInt);
// myInt has a value of 42.

请参见

参考

System.Convert

其他资源

转换类型