【发布时间】:2012-05-16 10:33:12
【问题描述】:
我遇到了DecimalConverter 和Int32Converter 类的问题,它们似乎返回了不一致的结果,如下面的简单控制台程序所示:
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
除非我对 TypeConverters 的理解有误,否则以下内容应该成立:
TypeDescriptor.GetConverter(typeof(TypeA)).CanConvertFrom(typeof(TypeB))
应该给出与
相同的结果TypeDescriptor.GetConverter(typeof(TypeB)).CanConvertTo(typeof(TypeA))
至少在System.Int32 和System.Decimal 的情况下,它们不会。
我的问题是:有人知道这是否是设计使然吗?还是 C# 中原生类型的 TypeConverters 真的坏了?
【问题讨论】:
-
我不明白在反序列化 JSON 时为什么需要将
int转换为decimal,因为 JSON 包含字符串,而不是ints。 -
我已经扩展了我的问题以澄清。我意识到我可以通过确保将所有内容作为字符串序列化到浏览器中来处理这个问题,但这不是真正的问题,更多的是前奏。
标签: c# .net typeconverter