【问题标题】:Can you assign a TypeConverter without a TypeConverterAttribute?您可以分配没有 TypeConverterAttribute 的 TypeConverter 吗?
【发布时间】:2011-03-05 08:25:18
【问题描述】:

依赖要求迫使我拥有一个不同的类及其 TypeConverter 程序集。

有没有办法在不使用 TypeConverterAttribute 的情况下将 TypeConverter 分配给类,从而导致循环程序集引用。

谢谢。

【问题讨论】:

    标签: c# typeconverter


    【解决方案1】:

    嗯,我不确定我以前见过这个,但你可以在运行时使用 TypeDescriptor 添加 TypeConverterAttribute,所以给定我的示例类:

    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);
        }
    }
    

    然后我可以有一个方法:

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

    希望对您有所帮助。

    【讨论】:

    • 然而,这不适用于 XAML,因为 XAML 不考虑运行时的组件修改。我 found a way around this 使用 TypeConverter 将其实现重定向到使用 TypeDescriptor 加载的转换器。
    【解决方案2】:

    您仍然可以使用TypeConverterAttribute 并使用其接受完全限定名称的构造函数。见MSDN

    【讨论】:

    • 那是否还需要引用包含类型转换器的程序集?
    • 否,包含类型转换器的程序集将在运行时通过 Type.GetType (msdn.microsoft.com/en-us/library/w3f99sx1.aspx) 加载。
    • @Spike,不,因为类型转换器类型可以通过名称而不是 typeof(...) 来引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2010-12-17
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多