温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#如何实现强制转换

发布时间:2021-12-01 13:56:29 来源:亿速云 阅读:3585 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关C#如何实现强制转换的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

int 关键字表示一种整型,是32位的,它的 .NET Framework 类型为 System.Int32。

(int)表示使用显式强制转换,是一种类型转换。当我们从int类型到long、float、double 或decimal 类型,可以使用隐式转换,但是当我们从long类型到int类型转换就需要使用显式强制转换,否则会产生编译错误。

Int32.Parse()表示将数字的字符串转换为32 位有符号整数,属于内容转换[1]。

我们一种常见的方法:public static int Parse(string)。

如果string为空,则抛出ArgumentNullException 异常;

如果string格式不正确,则抛出FormatException 异常;

如果string的值小于MinValue或大于MaxValue的数字,则抛出OverflowException异常。

Convert.ToInt32() 则可以将多种类型(包括 object  引用类型)的值转换为 int  类型,因为它有许多重载版本[2]:

public static int ToInt32(object);    public static int ToInt32(bool);    public static int ToInt32(byte);    public static int ToInt32(char);    public static int ToInt32(decimal);    public static int ToInt32(double);    public static int ToInt32(short);    public static int ToInt32(long);    public static int ToInt32(sbyte);    public static int ToInt32(string);    ......

(int)和Int32.Parse(),Convert.ToInt32()三者的应用举几个例子:   

例子一:

long longType = 100;  int intType  = longType;       // 错误,需要使用显式强制转换  int intType = (int)longType; //正确,使用了显式强制转换

例子二:

string stringType = "12345";   int intType = (int)stringType;                //错误,string 类型不能直接转换为 int  类型   int intType = Int32.Parse(stringType);   //正确

例子三:

long longType = 100;  string stringType = "12345";  object objectType = "54321";  int intType = Convert.ToInt32(longType);       //正确  int intType = Convert.ToInt32(stringType);     //正确  int intType = Convert.ToInt32(objectType);    //正确

例子四[1]:

double doubleType = Int32.MaxValue + 1.011;   int intType = (int)doubleType;                                //虽然运行正确,但是得出错误结果  int intType = Convert.ToInt32(doubleType)            //抛出 OverflowException 异常

C#强制转换中(int)和Int32.Parse(),Convert.ToInt32()三者的区别:

***个在对long 类型或是浮点型到int 类型的显式强制转换中使用,但是如果被转换的数值大于Int32.MaxValue 或小于 Int32.MinValue,那么则会得到一个错误的结果。

第二个在符合数字格式的string到int 类型转换过程中使用,并可以对错误的string数字格式的抛出相应的异常。

第三个则可以将多种类型的值转换为int类型,也可以对错误的数值抛出相应的异常。

无论进行什么类型的数值转换,数值的精度问题都是我们必须考虑的。

感谢各位的阅读!关于“C#如何实现强制转换”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI