Convert类是将一个基本数据类型转换为另一个基本数据类型。
例如如下的代码就行不通了:
- string text = "1412";
- int id = (int)text;
我们把上面的代码稍稍修改就可以达到目的了
- string text = "1412";
- int id = Convert.ToInt32(text);
下面的代码示例演示 Convert 类中的一些转换方法,包括 ToInt32、ToBoolean 和 ToString。
L例如:
double dNumber = 23.15;
try {
// Returns 23
int iNumber = System.Convert.ToInt32(dNumber);
}
catch (System.OverflowException) {
System.Console.WriteLine(
"Overflow in double to int conversion.");
}
// Returns True
bool bNumber = System.Convert.ToBoolean(dNumber);
// Returns "23.15"
string strNumber = System.Convert.ToString(dNumber);
try {
// Returns '2'
char chrNumber = System.Convert.ToChar(strNumber[0]);
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("String is null");
}
catch (System.FormatException) {
System.Console.WriteLine("String length is greater than 1.");
}
// System.Console.ReadLine() returns a string and it
// must be converted.
int newInteger = 0;
try {
System.Console.WriteLine("Enter an integer:");
newInteger = System.Convert.ToInt32(
System.Console.ReadLine());
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("String is null.");
}
catch (System.FormatException) {
System.Console.WriteLine("String does not consist of an " +
"optional sign followed by a series of digits.");
}
catch (System.OverflowException) {
System.Console.WriteLine(
"Overflow in string to int conversion.");
}
System.Console.WriteLine("Your integer as a double is {0}",
System.Convert.ToDouble(newInteger));