自己写了一个TypeConverter,编译通过,运行时报错误,为什么呢
自己写了一个TypeConverter,编译通过,运行时报异常,为什么呢?
我自己写了一个非常简单的Human类,希望通过写一个Converter来把一个string转换为Human实例,如下的代码。
我不想显示创建一个converter,而是通过一个TypeConverterAttribute来实现转换:
运行结果是命令行显示exception的信息
Unhandled Exception: System.NotSupportedException: 'StringToHumanTypeConverter' is unable to convert 'System.String' to 'ConsoleApplication1.Human'.
at System.ComponentModel.TypeConverter.GetConvertToException(Object value, Type destinationType)
at System.ComponentModel.TypeConverter.ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType)
at ConsoleApplication1.Program.Main(String[] args) in d:\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 45
我调试发现" TypeDescriptor.GetConverter(typeof(Human))"么有异常,异常是出在"ConvertTo(v,typeof(Human))"这一句
这是为什么呢? 是我的用法有错误吗,代码改如何改?
------解决方案--------------------
TypeDescriptor.GetConverter(typeof(string)).ConvertTo(v,typeof(Human));
------解决方案--------------------
楼主傻了啵,明明重载了的是 ConvertFrom 方法,是从 string 转到 Human 的,临了居然调用 ConvertTo 了?
我自己写了一个非常简单的Human类,希望通过写一个Converter来把一个string转换为Human实例,如下的代码。
我不想显示创建一个converter,而是通过一个TypeConverterAttribute来实现转换:
namespace ConsoleApplication1
{
public class StringToHumanTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return true;
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
Human h = new Human();
h.Name = value as string;
return h;
}
return base.ConvertFrom(context, culture, value);
}
}
[TypeConverter(typeof(StringToHumanTypeConverter))]
public class Human
{
public string Name { get; set; }
public Human Child { get; set; }
}
class Program
{
static void Main(string[] args)
{
string v = "abc";
Human h = (Human)TypeDescriptor.GetConverter(typeof(Human)).ConvertTo(v,typeof(Human));
}
}
}
运行结果是命令行显示exception的信息
Unhandled Exception: System.NotSupportedException: 'StringToHumanTypeConverter' is unable to convert 'System.String' to 'ConsoleApplication1.Human'.
at System.ComponentModel.TypeConverter.GetConvertToException(Object value, Type destinationType)
at System.ComponentModel.TypeConverter.ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType)
at ConsoleApplication1.Program.Main(String[] args) in d:\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 45
我调试发现" TypeDescriptor.GetConverter(typeof(Human))"么有异常,异常是出在"ConvertTo(v,typeof(Human))"这一句
这是为什么呢? 是我的用法有错误吗,代码改如何改?
------解决方案--------------------
TypeDescriptor.GetConverter(typeof(string)).ConvertTo(v,typeof(Human));
------解决方案--------------------
楼主傻了啵,明明重载了的是 ConvertFrom 方法,是从 string 转到 Human 的,临了居然调用 ConvertTo 了?