Can you assign a TypeConverter without a TypeConverterAttribute?

后端 未结 2 1527
名媛妹妹
名媛妹妹 2020-12-16 14:53

Dependency requirements are forcing me to have a class and its TypeConverter in different assemblies.

Is there a way to assign a TypeConverter to a class without us

相关标签:
2条回答
  • 2020-12-16 15:16

    Hmm, not sure I've seen this before, but you could add the TypeConverterAttribute at runtime using a TypeDescriptor, so given my sample classes:

    public class MyType
    {
        public string Name;
    }
    
    public class MyTypeConverter : 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, System.Globalization.CultureInfo culture, object value)
        {
            if (value.GetType() == typeof(string))
                return new MyType() { Name = (string) value };
    
            return base.ConvertFrom(context, culture, value);
        }
    }
    

    I could then have a method:

    public void AssignTypeConverter<IType, IConverterType>()
    {
      TypeDescriptor.AddAttributes(typeof(IType), new TypeConverterAttribute(typeof(IConverterType)));
    }
    
    AssignTypeConverter<MyType, MyTypeConverter>();
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-16 15:18

    You can still use TypeConverterAttribute and use its constructor which accepts a fully qualified name. See MSDN.

    0 讨论(0)
提交回复
热议问题