• Int.Parse()、Convert.toInt32()和(int)区别


    通过网上的查询从而了解了Int.Parse()、Convert.toInt32()和(int)区别。

    一、定义上的差别

    int类型表示一种整型,.NET Framework 类型为 System.Int32。而是用(int)表示显式强制类型转换,当从 int 类型到 long、float、double 或decimal 类型,称为隐式转换;当从从double 或decimal、float、long、int类型逐级转换时,称为显式强制类型转换。(对long 类型或是浮点型到int 类型的显式强制转换中使用,但是如果被转换的数值大于 Int32.MaxValue 或小于 Int32.MinValue,那么则会得到一个错误的结果)

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

    Convert.toInt32()表示可以将多种类型(包括 object  引用类型)的值转换为 int  类型。

    Int32.TryParse 与 int.Parse 又较为类似,但它不会产生异常,转换成功返回 true,转换失败返回 false。

    二、Int.Parse()与Convert.toInt32()的差别

       1、Int.Parse()当传入的是Null,将会抛出异常;Convert.toInt32()当传入的是Null,将返回0。

            例如:Int.Parse(null)抛出异常,Convert.toInt32(null)==0,返回true。

    2、Int.Parse()传入的是” ”,将会抛出异常;Convert.toInt32()传入的是” ”,也将抛出异常。

        例如:Int.Parse(“”)与Convert.toInt32(“”)都将抛出异常。

    3、性能差异:

    Int32.TryParse()优于Int32.Parse()优于Convert.ToInt32()。

    Convert.ToInt32会把最终的解析工作代理给Int32.Parse,而Int32.Parse和Int32.TryParse则分别把解析工作直接代理给Number.ParseInt32和Number.TryParseInt32,前者在出现解析,错误时会抛出异常,而后者则仅仅返回 false。

    三、差别的常见例子:

    1、long   longtype=100;

        Int   inttype=longtype;     //错误的写法,因为没有进行显式强制转换

        Int   inttype=(int)longtype; //正确的写法

    2、string  stringtype=”12345”;

       Int   inttype=(int)stringtype;   //错误,string不能直接转换为int

       Int   inttype=Int.Parse(stringtype);  //正确

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

    4、double doubleType = Int32.MaxValue + 1.011; 

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

  • 相关阅读:
    .NET微服务调查结果
    发布基于Orchard Core的友浩达科技官网
    Followme Devops实践之路
    积极参与开源项目,促进.NET Core生态社区发展
    Service Fabric 与 Ocelot 集成
    “.Net 社区大会”(dotnetConf) 2018 Day 1 主题演讲
    Project file is incomplete. Expected imports are missing 错误解决方案
    稳定工作和创业之间的抉择
    回顾4180天在腾讯使用C#的历程,开启新的征途
    ML-Framework:ML.NET 0.3 带来新组件
  • 原文地址:https://www.cnblogs.com/li1002/p/4395844.html
Copyright © 2020-2023  润新知