C# Convert类简介

Convert类是将一个基本数据类型转换为另一个基本数据类型。

例如如下的代码就行不通了:

  1. string text = "1412";  
  2. int id = (int)text;

我们把上面的代码稍稍修改就可以达到目的了

  1. string text = "1412";  
  2. int id = Convert.ToInt32(text);

下面的代码示例演示 Convert 类中的一些转换方法,包括 ToInt32ToBooleanToString

代码
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));

 


posted @ 2010-03-12 22:15  平凡人生  阅读(1095)  评论(0编辑  收藏  举报