using System; using System.ComponentModel; using System.Globalization; using System.Drawing;
publicclassPointConverter : TypeConverter { // Overrides the CanConvertFrom method of TypeConverter. // The ITypeDescriptorContext interface provides the context for the // conversion. Typically, this interface is used at design time to // provide information about the design-time container. publicoverrideboolCanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { returntrue; } returnbase.CanConvertFrom(context, sourceType); } // Overrides the ConvertFrom method of TypeConverter. publicoverrideobjectConvertFrom(ITypeDescriptorContext context, CultureInfo culture, objectvalue) { if (valueisstring) { string[] v = ((string)value).Split(newchar[] {','}); returnnew Point(int.Parse(v[0]), int.Parse(v[1])); } returnbase.ConvertFrom(context, culture, value); } // Overrides the ConvertTo method of TypeConverter. publicoverrideobjectConvertTo(ITypeDescriptorContext context, CultureInfo culture, objectvalue, Type destinationType) { if (destinationType == typeof(string)) { return ((Point)value).X + "," + ((Point)value).Y; } returnbase.ConvertTo(context, culture, value, destinationType); } }
public MyPropertyEnum MyProperty { set { // Checks to see if the value passed is valid. if (!TypeDescriptor.GetConverter(typeof(MyPropertyEnum)).IsValid(value)) { thrownew ArgumentException(); } // The value is valid. Insert code to set the property. } }
Color c = Color.Red; Console.WriteLine(TypeDescriptor.GetConverter(typeof(Color)).ConvertToString(c));
还可以使用类型转换器从其名称转换值,如下一个代码示例所示。
C#复制
1
Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
在下面的代码示例中,可以使用类型转换器输出对象支持的标准值集。
C#复制
1 2 3
foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues()) { Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c)); }