可将要转换的值传递给 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.