使用 System.Convert 转换数据类型
更新:2007 年 11 月
System.Convert 类为支持的转换提供了一整套方法。它提供一种与语言无关的方法来执行转换,而且可用于针对公共语言运行时的所有语言。虽然不同的语言可能会使用不同的技术来转换数据类型,但 Convert 类可确保所有的公共转换都可通过一般格式来使用。该类执行扩大转换、收缩转换以及不相关数据类型的转换。例如,支持从 String 转换为数字类型、从 DateTime 类型转换为 String 类型以及从 String 类型转换为 Boolean 类型。有关可用转换的列表,请参见 Convert 类中的方法列表。Convert 类执行检查过的转换,并在转换不受支持时总会引发异常。异常通常为 OverflowException。有关支持的转换的列表,请参见类型转换表。
可将要转换的值传递给 Convert 类中的某一相应方法,并将返回的值初始化为新变量。例如,下面的代码使用 Convert 类将 String 值转换为 Boolean 值。
Dim myString As String = "true"
Try
Dim myBool As Boolean = Convert.ToBoolean(myString)
Console.WriteLine(myBool)
Catch e As FormatException
Console.WriteLine("{0} is not a Boolean value.", myString)
End Try
' myBool has a value of True.
string myString = "true";
try
{
bool myBool = Convert.ToBoolean(myString);
Console.WriteLine(myBool);
}
catch (FormatException)
{
Console.WriteLine("{0} is not a Boolean value.", myString);
}
// myBool has a value of True.
如果您要将字符串转换为数字值,Convert 类也十分有用。下面的代码示例将包含数字字符的字符串转换为 Int32 值。
Dim newString As String = "123456789"
Try
Dim myInt As Integer = Convert.ToInt32(newString)
Console.WriteLine(myInt)
Catch e As FormatException
Console.WriteLine("{0} does not represent a number.", newString)
Catch e As OverflowException
Console.WriteLine("{0} is out of range of the integer type.", _
newString)
End Try
' myInt has a value of 123456789.
string newString = "123456789";
try
{
int myInt = Convert.ToInt32(newString);
Console.WriteLine(myInt);
}
catch (FormatException)
{
Console.WriteLine("{0} does not represent a number.",
newString);
}
catch (OverflowException)
{
Console.WriteLine("{0} is out of range of the integer type.",
newString);
}
// myInt has a value of 123456789.
也可将 Convert 类用于无法以您所使用的特定语言来隐式执行的收缩转换。下面的代码示例显示了使用 Convert.ToInt32 方法的从 Int64 至较小的 Int32 的收缩转换。
Dim myInt64 As Int64 = 123456789
Try
Dim myInt As Integer = Convert.ToInt32(myInt64)
Console.WriteLine(myInt)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to an integer.", _
myInt64)
End Try
' MyInt has a value of 123456789.
Int64 myInt64 = 123456789;
try
{
int myInt = Convert.ToInt32(myInt64);
Console.WriteLine(myInt);
}
catch (OverflowException)
{
Console.WriteLine("Unable to convert {0} to a 32-bit integer.",
myInt64);
}
// myInt has a value of 123456789.
有时,执行有 Convert 类的收缩转换会改变所转换项目的值。下面的代码示例将 Double 值转换为 Int32 值。这种情况下,值从 42.72 四舍五入为 43 以完成转换。
Dim myDouble As Double = 42.72
Try
Dim myInt As Integer = Convert.ToInt32(myDouble)
Console.WriteLine(myInt)
Catch e As OverflowException
Console.WriteLine("Unable to convert {0} to an integer.", myDouble)
End Try
' MyInt has a value of 43.
Double myDouble = 42.72;
try
{
int myInt = Convert.ToInt32(myDouble);
Console.WriteLine(myInt);
}
catch (OverflowException)
{
Console.WriteLine("Unable to convert {0} to an integer.", myDouble);
}
// myInt has a value of 43.