【www.gdgbn.com--计数转换】

asp教程.net c# int类型转换

int i = -1; bool b = int.tryparse(null, out i);

执行完毕后,b等于false,i等于0,而不是等于-1,切记。

int i = -1; bool b = int.tryparse("123", out i);

 执行完毕后,b等于true,i等于123;

1、(int)是一种类型转换;当我们类型到long,float,double,decimal类型,可以使用隐式转换,但是当我们从long类型到int类型就需要使用显式转换,否则会产生编译错误。 2、int.parse()是一种类容转换;表示将数字内容的字符串转为int类型。

 如果字符串为空,则抛出argumentnullexception异常;

如果字符串内容不是数字,则抛出formatexception异常;

 如果字符串内容所表示数字超出int类型可表示的范围,则抛出overflowexception异常;

3、int.tryparse与 int.parse 又较为类似,但它不会产生异常,

转换成功返回 true,转换失败返回 false。

最后一个参数为输出值,如果转换失败,输出值为 0,如果转换成功,输出值为转换后的int值

 4、convert.toint32()是一种类容转换;但它不限于将字符串转为int类型,还可以是其它类型的参数;

 比较:convert.toint32 参数为 null 时,返回 0; int.parse 参数为 null 时,抛出异常。convert.toint32 参数为 "" 时,抛出异常; int.parse 参数为 "" 时,抛出异常。 convert.toint32 可以转换的类型较多; int.parse 只能转换数字类型的字符串

convert.toint32来强制转换,但发现当字符串值以小数,科学计数法表示时候无法转换。如果在toint32之前先将字符串转换为detimal就不会有这种情况。

public static int do(string value)
        {
            if (string.isnullorempty(value)) return 0;

            decimal result = 0;
            try { decimal.tryparse(value, out result); }
            catch { }
            return system.convert.toint32(result);
        }

我的转换类全部代码

namespace cs.convert
{
    public class toint
    {
        public static int do(string value)
        {
            if (string.isnullorempty(value)) return 0;

            decimal result = 0;
            try { decimal.tryparse(value, out result); }
            catch { }
            return system.convert.toint32(result);
        }

        public static int do(decimal value)
        {
            return system.convert.toint32(value);
        }

        public static int do(float value)
        {
            return system.convert.toint32(value);
        }

        public static int do(double value)
        {
            return system.convert.toint32(value);
        }

        public static int do(int value)
        {
            return value;
        }

        public static int do(object value)
        {
            if (null == value || string.isnullorempty(value.tostring())) return 0;
            decimal result = 0;
            try { decimal.tryparse(value.tostring(), out result); }
            catch { }
            return system.convert.toint32(result);
        }

        public static int do(dbnull value)
        {
            return 0;
        }
    }
}

本文来源:http://www.gdgbn.com/wangyetexiao/28850/