【发布时间】:2017-09-24 18:05:58
【问题描述】:
我正在努力在 C# 中实现一个简单的类型转换器。 我按照本指南https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx
这是我的课:
public class TestClass: TypeConverter
{
public string Property1{ get; set; }
public int Property2 { get; set; }
public TestClass(string p1, int p2)
{
Property1= p1;
Property2 = p2;
}
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string) {
return new TestClass ("", Int32.Parse(value.ToString()));
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string)) {
return "___"
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
我做以下TestClass ("", Int32.Parse(value.ToString()));,目前我只对"1231" -> new TestClass("", 1231)这样的案例感兴趣
这里是给我一个异常的代码;
TypeConverter converter=TypeDescriptor.GetConverter( typeof(TestClass));
Object lalala = converter.ConvertFromString("234");
这段代码抛出NotSupportedException,但我不明白为什么
【问题讨论】:
标签: c# typeconverter