Tôi đang chạy vào một vấn đề với DecimalConverter
và Int32Converter
lớp học, mà dường như được trở về kết quả không phù hợp, như chứng minh bởi các chương trình sau đây đơn giản giao diện điều khiển:Loại Biến tần bị hỏng cho các kiểu nguyên thủy?
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)));
}
}
Kết quả từ này như sau:
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
Trừ khi tôi hiểu TypeConverters không đúng, sau đây nên giữ đúng:
TypeDescriptor.GetConverter(typeof(TypeA)).CanConvertFrom(typeof(TypeB))
nên cho kết quả tương tự như
TypeDescriptor.GetConverter(typeof(TypeB)).CanConvertTo(typeof(TypeA))
Ít nhất là trong trường hợp của System.Int32
và System.Decimal
, họ không.
Câu hỏi của tôi là: Có ai biết nếu điều này là do thiết kế? Hoặc là TypeConverters cho các loại bản địa trong C# thực sự bị hỏng?
Tôi không hiểu làm thế nào bạn cần phải chuyển đổi 'int' thành' thập phân' khi deserializing JSON, vì JSON chứa chuỗi chứ không phải 'int'. – svick
Tôi đã mở rộng câu hỏi của mình để làm rõ. Tôi nhận ra rằng tôi có thể xử lý điều này bằng cách đảm bảo rằng tôi sắp xếp mọi thứ như một chuỗi trên đường xuống trình duyệt, nhưng đó không thực sự là câu hỏi, một khúc dạo đầu hơn. – rossipedia