在运行时将EnConverter属性添加到枚举

在C#/ WPF应用程序中,我为一些枚举添加了TypeConverter属性,以便显示本地化文本而不是枚举文本:

[TypeConverter(typeof(LocalizedEnumTypeConverter))] public enum MyEnum { EnumVal1 = 0, EnumVal2 = 1, EnumVal3 = 2, } 

我已经实现了LocalizedEnumTypeConverter来执行此任务。

当我尝试使用与另一个程序集中定义的枚举相同的方法时出现问题,该枚举无法访问LocalizedEnumTypeConverter,并且与其他应用程序共享(也就是说,我无法添加对LocalizedEnumTypeConverter所在的程序集的引用)定义)。

有没有办法在运行时添加TypeConverter属性? 这样我可以在没有TypeConverter属性的情况下将枚举保留在其他程序集中,然后在我的应用程序中将其添加到运行时。

这可以使用TypeDescriptor类https://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx完成 。 请参阅以下示例。

  Attribute[] newAttributes = new Attribute[1]; newAttributes[0] = new TypeConverterAttribute(typeof(LocalizedEnumTypeConverter)); TypeDescriptor.AddAttributes(MyEnum, newAttributes);