WinForm控件开发总结(六) 控件属性类型转换器代码详解2011-11-14 博客园 纶巾客在上一篇文章,我为控件添加一个一个复杂属性,并且为这个属性的类型的编写了一个类型转换器, 现在我们来看看这个类型转换器的代码,并解释一下这些代码的意义。要实现一个类型转换器,我们必须要重写(override)四个方法:CanConvertFrom()――根据类型参数进行测试,判断是否能从这个类型转换成当前类型,在本例中我 们只提供转换string和InstanceDescriptor类型的能力。CanConvertTo()――根据类型参数进行测试,判断是否能从当前类型转换成指定的类型。ConvertTo()――将参数value的值转换为指定的类型。ConvertFrom()――串换参数value,并返回但书类型的一个对象。
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { String result = ""; if (destinationType == typeof(String)) { Scope scope = (Scope)value; result = scope.Min.ToString()+"," + scope.Max.ToString(); return result; } if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ci = typeof(Scope).GetConstructor(new Type[] {typeof(Int32),typeof(Int32) }); Scope scope = (Scope)value; return new InstanceDescriptor(ci, new object[] { scope.Min,scope.Max }); } return base.ConvertTo(context, culture, value, destinationType); }