2015-10-20 216 views
2

如何將一些負數轉換爲unsigned types將負數轉換爲無符號類型(ushort,uint或ulong)

Type type = typeof (ushort); 
short num = -100; 

ushort num1 = unchecked ((ushort) num); //When type is known. Result 65436 

ushort num2 = unchecked(Convert.ChangeType(num, type)); //Need here the same value 
+2

您在第二個示例中沒有使用反射。 – Servy

+3

「此代碼不起作用」 - 以何種方式?你期望什麼結果,發生了什麼? –

+1

ChangeType返回對象不是ushort –

回答

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 

更新2017年10月10日

與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; 
} 
+0

四次「檢查類型,開箱,轉換,框」是相當醜陋。我想知道這種方法的用途是什麼。 –

+0

@JeppeStigNielsen我已經更新了答案。這應該現在更好。我不認爲任何比這更好的方式,這可能是一個xy問題也許不是。 OP可能具有未知類型或那只是一種練習。 –

+1

我不明白。你爲什麼使用'unchecked'?投射到無符號類型不會溢出或任何東西。但從無符號鑄造將得到它.. – sotn