数据类型转换的三种方式 Convert,parse和TryParse的解析
以Int类型为例,具体说明Convert.ToInt32(object value),int.Parse(object value)和int.TryParse(string s,out int result)的用法
一.int.Parse
int.Parse的底层实现原理(可以直接忽略,不需深究)
[SecuritySafeCritical]
internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = ;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
int.Parse()是一种类容转换;表示将数字内容的字符串转为int类型。
如果字符串为空,则抛出ArgumentNullException异常;
如果字符串内容不是数字,则抛出FormatException异常;
如果字符串内容所表示数字超出int类型可表示的范围,则抛出OverflowException异常;
二.Convert.ToInt32
Convert.ToInt32实现方式是这样的(反射源程序集可知):
public static int ToInt32(string value)
{
if (value == null)
{
return ;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
从上面的代码可以看出Convert.toInt32其实可以看作是对 int.Parse一个改进,因为它判断了值等于null的情况
Convert.ToInt32 参数为 null 时,返回 0
但当Convert.ToInt32参数为string.empty是,就会抛出System.FormatException: 输入字符串的格式不正确异常。
三. int.TryParse
[SecuritySafeCritical]
internal static unsafe bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
{
byte* stackBuffer = stackalloc byte[0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
result = ;
if (!TryStringToNumber(s, style, ref number, info, false))
{
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref result))
{
return false;
}
}
else if (!NumberToInt32(ref number, ref result))
{
return false;
}
return true;
}
int.TryParse 可以看作是对int.Parse和Convert.toInt32的改进。
它既判断了值等于null的情况,还判断了string.empty 这样空字符的情况。
所以它不会产生异常,转换成功返回 true,转换失败返回 false。
最后一个参数为输出值,如果转换失败,输出值为 0,如果转换成功,输出值为转换后的int值
四.int.Parse,Convert.ToInt和int.TryParse的比较
1.参数和适用对象不同
int.Parse的参数数据类型只能是string类型,适用对象为string类型的数据
convert.toInt参数比较多,具体可以参见最下面的重载列表
int.TryParse的参数只能是只能是string类型,适用对象为string类型的数据
2.异常情况不同
异常主要是针对数据为null或者为""的情况
Convert.ToInt32 参数为 null 时,返回 0;Convert.ToInt32 参数为 "" 时,抛出异常;
int.Parse 参数为 null 时,抛出异常。; int.Parse 参数为 "" 时,抛出异常。
int.TryParse
3.返回值不同
int.TryParse与int.Parse和Convert.ToInt 在返回值的不同是返回bool类型。获取转换后的值是通过out result这个参数获取的。
五.附
Convert.ToInt 参数重载列表
名称 | 描述 | |
---|---|---|
![]() ![]() |
ToInt32(Boolean) | 将指定的布尔值转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(Byte) | 将指定的 8 位无符号整数的值转换为等效的 32 位有符号整数。 |
![]() ![]() |
ToInt32(Char) | 将指定的 Unicode 字符的值转换为等效的 32 位有符号整数。 |
![]() ![]() |
ToInt32(DateTime) | 调用此方法始终引发 InvalidCastException。 |
![]() ![]() |
ToInt32(Decimal) | 将指定的十进制数的值转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(Double) | 将指定的双精度浮点数的值转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(Int16) | Converts the value of the specified 16-bit signed integer to an equivalent 32-bit signed integer. |
![]() ![]() |
ToInt32(Int32) | 返回指定的 32 位有符号整数;不执行实际的转换。 |
![]() ![]() |
ToInt32(Int64) | Converts the value of the specified 64-bit signed integer to an equivalent 32-bit signed integer. |
![]() ![]() |
ToInt32(Object) | 将指定对象的值转换为 32 位带符号整数。 |
![]() ![]() |
ToInt32(SByte) | 将指定的 8 位带符号整数的值转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(Single) | 将指定的单精度浮点数的值转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(String) | 将数字的指定字符串表示形式转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(UInt16) | 将指定的 16 位无符号整数的值转换为等效的 32 位有符号整数。 |
![]() ![]() |
ToInt32(UInt32) | 将指定的 32 位无符号整数的值转换为等效的 32 位有符号整数。 |
![]() ![]() |
ToInt32(UInt64) | Converts the value of the specified 64-bit unsigned integer to an equivalent 32-bit signed integer. |
![]() ![]() |
ToInt32(Object, IFormatProvider) | 使用指定的区域性特定格式信息,将指定对象的值转换为 32 位带符号整数。 |
![]() ![]() |
ToInt32(String, IFormatProvider) | 使用指定的区域性特定格式设置信息,将数字的指定字符串表示形式转换为等效的 32 位带符号整数。 |
![]() ![]() |
ToInt32(String, Int32) | 将指定基数的数字的字符串表示形式转换为等效的 32 位有符号整数。 |
数据类型转换的三种方式 Convert,parse和TryParse的解析的更多相关文章
- PHP中数据类型转换的三种方式
PHP中数据类型转换的三种方式 PHP的数据类型转换属于强制转换,允许转换的PHP数据类型有: 1.(int).(integer):转换成整形2.(float).(double).(real):转换成 ...
- PHP判断变量类型和类型转换的三种方式
前言: PHP 在变量定义中不需要(不支持)明确的类型定义.变量类型是根据使用该变量的上下文所决定的.所以,在面对页码跳转.数值计算等严格的格式需求时,就要对变量进行类型转换. 举例如下: $foo ...
- entity framework 数据加载三种方式的异同(延迟加载,预加载,显示加载)
三种加载方式的区别 显示加载: 显示加载
- django基础之day09,多对多创建数据表的三种方式
多对多三种创建方式 1.全自动(用在表关系不复杂的一般情况) class Book(models.Model): title=models.CharField(max_length=32) 多对多关系 ...
- JS数据交换的三种方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- ASP.NET MVC 数据传递进阶 从数据库拿到数据后的三种方式
目录 回顾 数据 显示 因为这个小练习有EF的一些东西,我们来回顾一下. 一.回顾 回顾一点EF的知识怎么生成数据库模型. 1.首先我们在Models文件夹右键添加新建项,在数据分栏下有ADO.NET ...
- Android数据存储的三种方式:SharePreferences , file , SQLite
(1)SharePreferences: 存入: SharedPreferences setter = this.getSharedPreferences("spfile", 0) ...
- Mysql 删除数据表的三种方式详解
用法: 1.当你不再需要该表时, 用 drop; 2.当你仍要保留该表,但要删除所有记录时, 用 truncate; 3.当你要删除部分记录或者有可能会后悔的话, 用 delete. 删除强度:dro ...
- PHP如何实现数据类型转换(字符转数字,数字转字符)(三种方式)
PHP如何实现数据类型转换(字符转数字,数字转字符)(三种方式) 一.总结 一句话总结: 1.强制转换:(int) (bool) (float) (string) (array) (object) 2 ...
随机推荐
- [转]Jenkins CommonCollections 完美利用(演示)工具
博主URL:http://tools.changesec.com/Jenkins-CommonCollections-Exploit/ 提交漏洞总是要证明漏洞危害,老外写的java代码又有bug,所以 ...
- Javascript获取地址栏参数值
采用正则表达式获取地址栏参数: function GetQueryString(name) { var reg = new RegExp("(^|&)"+ name +&q ...
- run a Freight robot (2)
3. Network Setup Connecting Freight to a Monitor The easiest way to configure the wireless networki ...
- iOS - OC NSTimeZone 时区
前言 @interface NSTimeZone : NSObject <NSCopying, NSSecureCoding> NSTimeZone 表示时区信息. 1.NSTimeZon ...
- [转载] C++ 程序员快过来围观:非常实用全面的 C++ 资源
原文: http://codecloud.net/c-plus-plus-resource-2983.html 绝对是c++开发者的福音啊, 必须推荐. 这次的资源涉及到了标准库.Web应用框架.人工 ...
- 对于syncedmen类的代码分析
对于数据在cpu与GPU之间同步的问题,caffe中用syncedMemory这个类来解 决:在GPU模式下,并且使用CUDA时,可以用CaffeMallocHost函数与CaffeFreeHost函 ...
- (十一)C语言中内存堆和栈的区别
在计算机领域,堆栈是一个不容忽视的概念,我们编写的C语言程序基本上都要用到.但对于很多的初学着来说,堆栈是一个很模糊的概念. 堆栈:一种数据结构.一个在程序运行时用于存放的地方,这可能是很多初学者的认 ...
- hdu 1588(Fibonacci矩阵求和)
题目的大意就是求等差数列对应的Fibonacci数值的和,容易知道Fibonacci对应的矩阵为[1,1,1,0],因为题目中f[0]=0,f[1]=1,所以推出最后结果f[n]=(A^n-1).a, ...
- NSString / NSData / char* 类型之间的转换
转自网络: NSString / NSData / char* 类型之间的转换 1. NSString转化为UNICODE String: (NSString*)fname = @“Test”; ch ...
- VIm vi 使用 汇总
x 删除当前光标下的字符dw 删除光标之后的单词剩余部分.d$ 删除光标之后的该行剩余部分.dd 删除当前行. c 功能和d相同,区别在于完成删除操作后进入INSERT MODEcc 也是删除当前行, ...