2012-02-05 16 views
0

我正在編譯C#中的轉換器,將整數,二進制和十六進制轉換爲相同的格式。當然,給出了輸入格式和輸出格式。 另一個有趣的一點是,我的輸入是string,我的輸出也是stringC中的整型二進制 - 六進制轉換器#

所以,現在我想知道是否有一種方法可以使用相同的函數來完成所有這些轉換,因爲在我探討的所有問題中,只給出了我的6個案例中的一個的解決方案,並且我沒有發現它非常優雅。

總結:

 
Input String | Output String 
-------------|-------------- 
int32  | hexa 
int32  | binary 
binary  | int32 
binary  | hexa 
hexa   | int32 
hexa   | binary 

編輯:所有異常將與try-catch代碼必要時進行處理。

+0

你是什麼意思「在一個功能」?如果你想獲得不同的轉換,你應該讓每個轉換都有自己的功能。 – annonymously 2012-02-05 00:20:19

+0

是的,但我想使用像'Convert.toString(inputType,inputValue,outputType)'相同的方法',而不必處理多個技巧從一種類型轉換爲另一種。 – 2012-02-05 00:24:43

+0

看來你正在尋找這個,但在C#中:http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/ – BlackBear 2012-02-05 00:34:21

回答

1

使其成爲一個兩步過程:從三種格式之一解析字符串,然後轉換爲三種格式之一。

要解析,您可以使用各自的Parse(或TryParse,如果您想避免例外情況下)存在的不同數值類型的方法。在整數類型上,可以使用NumberStyles.HexNumber從十六進制數字中解析。

要轉換爲字符串,請使用帶有適當文化和格式的重載ToString

請注意,您可以通過IConvertible接口進行類型轉換,該接口由所有本機號類型支持。

下面是一些僞代碼(不會編譯但應說明提出的各點):

enum NumberKind { 
    Int32, 
    Decimal, 
    Hexa 
} 

string ConvertNumber(NumberKind inputKind, string inputValue, NumberKind outputKind) { 
    IConvertible intermediate; 
    switch (inputKind) { 
    case NumberKind.Int32: 
    intermediate = Int32.Parse(inputValue, NumberStyles.Integer, CultureInfo.InvariantCulture); 
    break; 
    case NumberKind.Decimal: 
    intermediate = Decimal.Parse(inputValue, NumberStyles.Number, CultureInfo.InvariantCulture); 
    break; 
    case NumberKind.Hexa: 
    intermediate = Int32.Parse(inputValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture); 
    break; 
    } 
    switch (outputKind) { 
    case NumberKind.Int32: 
    return intermediate.ToInt32().ToString("D", CultureInfo.InvariantCulture); 
    case NumberKind.Decimal: 
    return intermediate.ToDecimal().ToString("G", CultureInfo.InvariantCulture); 
    case NumberKind.Hexa: 
    return intermediate.ToInt32().ToString("X", CultureInfo.InvariantCulture); 
    } 
} 
+0

非常感謝您的答案,你正式的我正在尋找的哲學。我編輯了我的問題,因爲我寫了'decimal'而不是'binary',但是你的答案是完美的。 – 2012-02-05 00:54:43

+0

我用這個解決方案完美地實現了我的轉換器,我只是補充說必須使用'使用System.Globalization;'才能使用NumberStyles。 – 2012-02-05 16:12:53

相關問題