c# how to implement type converter

后端 未结 2 548
旧巷少年郎
旧巷少年郎 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:15

    You have to attach this converter to a class with the TypeConverter attribute.
    TypeDescriptor.GetConverter Get the attached converter of the class.

    You better split the classes:

    [TypeConverter(typeof (TestClassConverter))]
    public class TestClass
    {
        public string Property1 { get; set; }
        public int Property2 { get; set; }
        public TestClass(string p1, int p2)
        {
            Property1 = p1;
            Property2 = p2;
        }
    }
    
    [TypeConverter(typeof (TestClassConverter))]
    public class TestClassConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context,
        Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context,
         CultureInfo culture, object value)
        {
            if (value is string)
            {
                return new TestClass("", Int32.Parse(value.ToString()));
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context,
        CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string)) { return "___"; }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
    

提交回复
热议问题