高效率的object转int的函数

在通常情况,object转int都会使用.net framework的Convert.ToInt32或者Int32.Parse()函数,但这不是最高效的方式,下面的两个方案不错

MS给出的答案:
public static ToInt32(object value)
{
    if(value != null)
    {
        return ((IConvertible)value).ToInt32(null);
    }
    return 0;
}

这种做法很OO,很优雅,但不能转换像"123.4"这样的数字字符,有一定缺陷;
另外一种是CSDN上的一位高手提供的:
static int ToInt(object o)
{
if (o is int)
return (int)o;
else if (o is short)
return (int)(short)o;
else if (o is byte)
return (int)(byte)o;
else if (o is long)
return (int)(long)o;
else if (o is double)
return (int)(double)o;
else if (o is float)
return (int)(float)o;
else if (o is decimal)
return (int)(decimal)o;
else if (o is uint)
return (int)(uint)o;
else if (o is ushort)
return (int)(ushort)o;
else if (o is ulong)
return (int)(ulong)o;
else if (o is sbyte)
return (int)(sbyte)o;
else
return (int)double.Parse(o.ToString());
}

这个方法就显得没那么优雅,但适应面广一些

以上摘抄至:竞赛:
要求用最高的效率写出object 转 int的函数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值