C# 是否可以在没有TypeConverterAttribute的情况下分配TypeConverter?
依赖性要求迫使我在不同的环境中拥有一个类及其类型转换器 装配 有没有一种方法可以在不使用TypeConverterAttribute的情况下将TypeConverter分配给类,从而导致循环程序集引用C# 是否可以在没有TypeConverterAttribute的情况下分配TypeConverter?,c#,typeconverter,C#,Typeconverter,依赖性要求迫使我在不同的环境中拥有一个类及其类型转换器 装配 有没有一种方法可以在不使用TypeConverterAttribute的情况下将TypeConverter分配给类,从而导致循环程序集引用 谢谢。嗯,我不确定以前是否见过这种情况,但您可以在运行时使用TypeDescriptor添加TypeConverterAttribute,因此给出了我的示例类: public class MyType { public string Name; } public class MyType
谢谢。嗯,我不确定以前是否见过这种情况,但您可以在运行时使用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>();
public void AssignTypeConverter()
{
AddAttributes(typeof(IType),newtypeconverterAttribute(typeof(IConverterType));
}
赋值类型转换器();
希望能有所帮助。您仍然可以使用
TypeConverterAttribute
并使用其接受完全限定名的构造函数。请参阅。这是否仍然需要引用包含typeconverter的程序集?否,包含typeconverter的程序集将在运行时通过Type.GetType()加载。@Spike,否,因为可以通过名称而不是typeof(…)引用类型转换器类型。但是,这不适用于XAML,因为XAML不考虑运行时的组件修改。我使用TypeConverter
将其实现重定向到使用TypeDescriptor
加载的转换器。