高效率的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的函数

posted @ 2006-01-12 22:03  kwklover  阅读(6070)  评论(0编辑  收藏  举报