我正在與DecimalConverter
和Int32Converter
類,這似乎是返回的結果不一致的問題,通過以下簡單的控制檯程序所示:TypeConverters破壞了原始類型?
using System;
using System.ComponentModel;
class App
{
static void Main()
{
var decConverter = TypeDescriptor.GetConverter(typeof(decimal));
Console.WriteLine("Converter: {0}", decConverter.GetType().FullName);
Console.WriteLine("CanConvert from int to decimal: {0}", decConverter.CanConvertFrom(typeof(int)));
Console.WriteLine("CanConvert to int from decimal: {0}", decConverter.CanConvertTo(typeof(int)));
Console.WriteLine();
var intConverter = TypeDescriptor.GetConverter(typeof(int));
Console.WriteLine("Converter: {0}", intConverter.GetType().FullName);
Console.WriteLine("CanConvert from int to decimal: {0}", intConverter.CanConvertTo(typeof(decimal)));
Console.WriteLine("CanConvert to int from decimal: {0}", intConverter.CanConvertFrom(typeof(decimal)));
}
}
從這裏輸出如下:
Converter: System.ComponentModel.DecimalConverter
CanConvert from int to decimal: False
CanConvert to int from decimal: True
Converter: System.ComponentModel.Int32Converter
CanConvert from int to decimal: False
CanConvert to int from decimal: False
除非我理解錯誤類型轉換器,下面應該成立:
TypeDescriptor.GetConverter(typeof(TypeA)).CanConvertFrom(typeof(TypeB))
應該給予同樣的結果
TypeDescriptor.GetConverter(typeof(TypeB)).CanConvertTo(typeof(TypeA))
在System.Int32
和System.Decimal
的情況下,至少,他們沒有。
我的問題是這樣的:有人知道這是否是由設計?或者C#中的本機類型的TypeConverters實際上是否被破壞?
我不明白爲什麼在反序列化JSON時需要將'int'轉換爲'decimal',因爲JSON包含字符串,而不是'int's。 – svick
我擴大了我的問題來澄清。我意識到,我可以通過確保將所有東西序列化爲一個字符串到瀏覽器的方式來處理這個問題,但這不是真正的問題,更像是一個前奏。 – rossipedia