将负数转换为无符号类型(ushort,uint或ulong)

时间:2015-10-20 17:50:07

标签: c# reflection

如何将一些负数转换为std::vector

unsigned types

1 个答案:

答案 0 :(得分:3)

只有4种类型。所以,你可以为此编写自己的方法。

private static object CastToUnsigned(object number)
{
    Type type = number.GetType();
    unchecked
    {
        if (type == typeof(int)) return (uint)(int)number;
        if (type == typeof(long)) return (ulong)(long)number;
        if (type == typeof(short)) return (ushort)(short)number;
        if (type == typeof(sbyte)) return (byte)(sbyte)number;
    }
    return null;
}

这是测试:

short sh = -100;
int i = -100;
long l = -100;

Console.WriteLine(CastToUnsigned(sh));
Console.WriteLine(CastToUnsigned(i));
Console.WriteLine(CastToUnsigned(l));

输出

65436
4294967196
18446744073709551516

更新10/10/2017

使用C#7.1模式匹配功能,您可以使用switch语句。

感谢@quinmars的建议。

private static object CastToUnsigned<T>(T number) where T : struct
{
    unchecked
    {
        switch (number)
        {
            case long xlong: return (ulong) xlong;
            case int xint: return (uint)xint;
            case short xshort: return (ushort) xshort;
            case sbyte xsbyte: return (byte) xsbyte;
        }
    }
    return number;
}
相关问题