取消一个数字加倍

Ale*_*kiy 0 .net c# boxing unboxing

是否有某种方法可以将未知数字转换成双倍?例如

    public static double Foo(object obj)
    {
        if (!obj.GetType().IsValueType)
            throw new ArgumentException("Argument should be a number", "obj");
        return (double) obj;
    }

    private static void Main(string[] args)
    {
        double dbl = 10;
        decimal dec = 10;
        int i = 10;
        short s = 10;
        Foo(dbl);
        Foo(dec);
        Foo(i);
        Foo(s);
    }
Run Code Online (Sandbox Code Playgroud)

但是当尝试将unbox打包为不正确的类型时,此代码会抛出异常.

Tim*_* S. 9

最简单的方法是使用Convert.ToDouble.这为您进行转换,并使用数字类型,strings和其他任何实现IConvertible(并且具有可转换为a的值double).

public static double Foo(object obj)
{
    // you could include a check (IsValueType, or whatever) like you have now,
    // but it's not generally necessary, and rejects things like valid strings
    return Convert.ToDouble(obj);
}
Run Code Online (Sandbox Code Playgroud)