您可以分配没有TypeConverterAttribute的TypeConverter? [英] Can you assign a TypeConverter without a TypeConverterAttribute?

查看:150
本文介绍了您可以分配没有TypeConverterAttribute的TypeConverter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关性要求迫使我有一个类和它在不同的
组件类型转换器。

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

是否有指定的TypeConverter一类没有办法使用TypeConverterAttribute,从而导致循环集引用。

Is there a way to assign a TypeConverter to a class without using a TypeConverterAttribute, and thus causing circular assembly references.

感谢。

推荐答案

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

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.

这篇关于您可以分配没有TypeConverterAttribute的TypeConverter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆