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";
var converter = new StringToHumanTypeConverter();//必须显示调用才能成功
if(converter.CanConvertFrom(typeof(string)))
{
Human h = (Human)converter.ConvertFrom(v);
}
//Human h = (Human)v;这句话就编译不过,尽管我加了Attribute。
}