【发布时间】:2011-03-05 08:25:18
【问题描述】:
依赖要求迫使我拥有一个不同的类及其 TypeConverter 程序集。
有没有办法在不使用 TypeConverterAttribute 的情况下将 TypeConverter 分配给类,从而导致循环程序集引用。
谢谢。
【问题讨论】:
标签: c# typeconverter
依赖要求迫使我拥有一个不同的类及其 TypeConverter 程序集。
有没有办法在不使用 TypeConverterAttribute 的情况下将 TypeConverter 分配给类,从而导致循环程序集引用。
谢谢。
【问题讨论】:
标签: c# typeconverter
嗯,我不确定我以前见过这个,但你可以在运行时使用 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>();
希望对您有所帮助。
【讨论】:
TypeConverter 将其实现重定向到使用 TypeDescriptor 加载的转换器。
您仍然可以使用TypeConverterAttribute 并使用其接受完全限定名称的构造函数。见MSDN。
【讨论】: