c# how to implement type converter

后端 未结 2 550
旧巷少年郎
旧巷少年郎 2020-12-31 20:35

I am struggling to implement a simple Type converter in C#. I followed this guide https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx

Here is my class :

2条回答
  •  甜味超标
    2020-12-31 21:00

    The code provided is a bit mixed up and it's missing some important stuff. Following, an implementation that converts a custom class CrazyClass from and to string.

    CrazyClassTypeConverter

    public class CrazyClassTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
        }
    
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var casted = value as string;
            return casted != null
                ? new CrazyClass(casted.ToCharArray())
                : base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            var casted = value as CrazyClass;
            return destinationType == typeof (string) && casted != null
                ? String.Join("", casted.Charray)
                : base.ConvertTo(context, culture, value, destinationType);
        }
    }
    

    CrazyClass

    (note that the class is decorated with TypeConverterAttribute)

    [TypeConverter(typeof(CrazyClassTypeConverter))]
    public class CrazyClass
    {
        public char[] Charray { get; }
    
        public CrazyClass(char[] charray)
        {
            Charray = charray;
        }
    }
    

    Usage

    var crazyClass = new CrazyClass(new [] {'T', 'e', 's', 't'});
    var converter = TypeDescriptor.GetConverter(typeof(CrazyClass));
    
    //this should provide you the string "Test"        
    var crazyClassToString = converter.ConvertToString(crazyClass); 
    
    //provides you an instance of CrazyClass with property Charray set to {'W', 'h', 'a', 't' } 
    var stringToCrazyClass = converter.ConvertFrom("What"); 
    

提交回复
热议问题