Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [TypeConverter(typeof(MyTypeConverter))]
- public class MyClass
- {
- }
- public class Converter : TypeConverter
- {
- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
- {
- if (sourceType == typeof(int)
- || sourceType == typeof(string)
- || sourceType == typeof(bool))
- {
- return true;
- }
- return base.CanConvertFrom(context, sourceType);
- }
- public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
- {
- if (destinationType == typeof(int)
- || destinationType == typeof(string)
- || destinationType == typeof(bool))
- {
- return true;
- }
- return base.CanConvertTo(context, destinationType);
- }
- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
- {
- if (destinationType == typeof(int))
- {
- return 42;
- }
- if (destinationType == typeof(string))
- {
- return "String is fine for convertion";
- }
- if (destinationType == typeof(bool))
- {
- return true;
- }
- return base.ConvertTo(context, culture, value, destinationType);
- }
- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
- {
- var sourceType = value.GetType();
- if (sourceType == typeof(int)
- || sourceType == typeof(string)
- || sourceType == typeof(bool))
- {
- return new Convertible() { ConvertionString = value.ToString() };
- }
- return base.ConvertFrom(context, culture, value);
- }
- }
- [TypeConverter(typeof(Converter))]
- public class Convertible
- {
- public string ConvertionString
- {
- get;
- set;
- }
- }
- var source = new Convertible();
- var intValue = TypeDescriptor.GetConverter(typeof(Convertible)).ConvertTo(source, typeof(int));
- var stringValue = TypeDescriptor.GetConverter(typeof(Convertible)).ConvertTo(source, typeof(string));
- var boolValue = TypeDescriptor.GetConverter(typeof(Convertible)).ConvertTo(source, typeof(bool));
- Console.WriteLine(intValue); //42
- Console.WriteLine(stringValue); //String is fine for convertion
- Console.WriteLine(boolValue); //True
- var fromIntValue = TypeDescriptor.GetConverter(typeof(Convertible)).ConvertFrom(42) as Convertible;
- var fromStringValue = TypeDescriptor.GetConverter(typeof(Convertible)).ConvertFrom("String is fine for convertion") as Convertible;
- var fromBoolValue = TypeDescriptor.GetConverter(typeof(Convertible)).ConvertFrom(true) as Convertible;
- Console.WriteLine(fromIntValue.ConvertionString); //42
- Console.WriteLine(fromStringValue.ConvertionString); //String is fine for convertion
- Console.WriteLine(fromBoolValue.ConvertionString); //True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement