你可以在没有TypeConverterAttribute的情况下分配TypeConverter吗?

时间:2010-06-18 09:18:39

标签: c# typeconverter

依赖性要求迫使我有一个类和它的TypeConverter不同 组件。

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

感谢。

2 个答案:

答案 0 :(得分:19)

嗯,不确定我以前见过这个,但你可以在运行时使用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>();

希望有所帮助。

答案 1 :(得分:3)

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

相关问题