2011-05-17 31 views
2

我需要在各種類型(十進制,int32,int64等)之間進行轉換,但我想確保不丟失任何數據。我發現正常的Convert方法(包括強制轉換)會在沒有警告的情況下截斷數據。如何在不丟失任何數據的情況下在兩種(數字)數據類型之間進行轉換?

decimal d = 1.5; 
int i = (int)d; 
// i == 1 

我想如果有一個轉換或TryConvert方法,如果轉換丟失數據會拋出或返回false。我怎樣才能做到這一點?

如果可能,我想這樣做的一般意義上,所以我可以做到這一切給予兩個Type對象和一個object實例(其中運行時類型是convertFrom類型)。像這樣:

object ConvertExact(object convertFromValue, Type convertToType) 
{ 
    if (** conversion not possible, or lossy **) 
     throw new InvalidCastException(); 

    // return converted object 
} 

this question類似,但這裏的數字被截斷。

回答

6

如何:

using System; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine(ConvertExact(2.0, typeof(int))); 
     Console.WriteLine(ConvertExact(2.5, typeof(int))); 
    } 

    static object ConvertExact(object convertFromValue, Type convertToType) 
    { 
     object candidate = Convert.ChangeType(convertFromValue, 
               convertToType); 
     object reverse = Convert.ChangeType(candidate, 
              convertFromValue.GetType()); 

     if (!convertFromValue.Equals(reverse)) 
     { 
      throw new InvalidCastException(); 
     } 
     return candidate; 
    } 
} 

請注意,這不是完美 - 這將既2.000米和2.00米,愉快地轉換爲2爲例,儘管事實,即確實丟失信息(精度)。儘管這並沒有失去任何影響,這對你來說可能已經足夠好了。

+0

謝謝!這個直接進入片段庫;) – 2011-05-17 17:59:57

相關問題