.Net Framework中Converter的使用

上一篇文章写了点转换的内容,但是没有解决字符数据转非字符数据的问题,现在这里给出解决方法。

转换问题在.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值