使用 System.Convert 转换
System.Convert 类为支持的转换提供了一整套方法。它提供一种与语言无关的方法来执行转换,而且可用于针对公共语言运行库的所有语言。虽然不同的语言可能会使用不同的技术来转换数据类型,但 Convert 类可确保所有的公共转换都可通过一般格式来使用。该类执行收缩转换以及不相关数据类型的转换。例如,从 String 类型到数字类型的转换,从 DateTime 类型到 String 类型的转换,从 String 类型到 Boolean 类型的转换,均可得到支持。有关可用转换的列表,请参见 Convert 类中的方法列表。Convert 类执行检查过的转换,并在转换不受支持时总会引发异常。异常通常为 OverflowException。有关支持的转换的列表,请参见类型转换表。
可将要转换的值传递给 Convert 类中的某一相应方法,并将返回的值初始化为新变量。例如,下列代码使用 Convert 类将 String 值转换为 Boolean 值。
[Visual Basic] Dim MyString As String = "true" Dim MyBool As Boolean = Convert.ToBoolean(MyString) ' MyBool has the value of True. [C#] string MyString = "true"; bool MyBool = Convert.ToBoolean(MyString); // MyBool has the value of True.
如果您要将字符串转换为数字值,Convert 类也十分有用。下列代码示例将包含数字字符的字符串转换为 Int32 值。
[Visual Basic] Dim newString As String = "123456789" Dim MyInt As Integer = Convert.ToInt32(newString) ' MyInt has the value of 123456789. [C#] string newString = "123456789"; int MyInt = Convert.ToInt32(newString); // MyInt has the value of 123456789.
也可将 Convert 类用于无法以您所使用的特定语言来隐式执行的收缩转换。下面的代码示例显示了使用 Convert.ToInt32 方法的从 Int64 至较小的 Int32 的收缩转换。
[Visual Basic] Dim MyInt64 As Int64 = 123456789 Dim MyInt As Integer = Convert.ToInt32(MyInt64) ' MyInt has the value of 123456789. [C#] Int64 MyInt64 = 123456789; int MyInt = Convert.ToInt32(MyInt64); // MyInt has the value of 123456789.
有时,执行有 Convert 类的收缩转换会改变所转换项目的值。下列代码示例将 Double 值转换为 Int32 值。这种情况下,值从 42.72 四舍五入为 43 以完成转换。
[Visual Basic] Dim MyDouble As Double = 42.72 Dim MyInt As Integer = Convert.ToInt32(MyDouble) ' MyInt has the value of 43. [C#] Double MyDouble = 42.72; int MyInt = Convert.ToInt32(MyDouble); // MyInt has the value of 43.
浙公网安备 33010602011771号