我遇到了DecimalConverter
andInt32Converter
类的问题,这似乎返回了不一致的结果,如下面的简单控制台程序所示:
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 是否真的损坏了?