如何创建接受多个值并序列化为 WinForms Form.designer.cs 的 TypeConverter?

How to create TypeConverter which accepts multiple values and serialized to WinForms Form.designer.cs?

我有摘要 class,其中有两个 child class。值和 StringValue 或 CustomValue。我想创建一个转换器来接受选择我需要的 class 并很好地序列化它。

有一个 的答案非常好(但让我添加更多行以确保它接受空值)

A型转换器

 public class ValueConverter: SortedExpandableObjectConverter
    {
        private Value[] standardValues = new Value[3] { null, new StringValue(), new CustomValue()};
        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)
        {
            switch (value.ToString().Replace(" ", ""))
            {
                case "(None)":
                    return null;
                case nameof(StringValue):
                    return new StringValue();
                case nameof(CustomValue):
                    return new CustomValue();
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value == null) return "(None)"; // to accept null value.
            return base.ConvertTo(context, culture, value, destinationType);
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection(standardValues);
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true;
    }

一个类

[TypeConverter(typeof(ValueConverter))]
public abstract class Value{}

public class StringValue : Value{ properties...}
public class CustomValue : Value{properties...}

   In UserControl declare property: 
   [DefaultValue(null)] // Is must for display null as grayed
   public Value MyValue{get;set;}