上一篇文章写了点转换的内容,但是没有解决字符数据转非字符数据的问题,现在这里给出解决方法。
转换问题在.net framework中提供了converter类,该类可以对类型进行任意转换。
但是该类不提供源类型数据与目标类型数据的匹配检查,例如
string t="aa123"; int tN;由于t中含有非数字字符,非数字字符无法转换为数字,因此两数据不匹配。
该类在不能进行转换时将抛出异常,因此进行转换时应该进行异常捕获。
下面是C#的转换例子:
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));
更多信息及例子可参看http://msdn2.microsoft.com/zh-cn/library/system.convert(VS.80).aspx