在运行时将TypeConverter属性添加到枚举 [英] Add TypeConverter attribute to enum in runtime
问题描述
在C#/ WPF应用程序中,我向我的一些枚举中添加了一个TypeConverter属性,以便显示一个本地化的文本而不是枚举的文本:
In a C#/WPF application I added a TypeConverter attribute to some of my enums in order to display a localized text instead of the text of the enum:
[TypeConverter(typeof(LocalizedEnumTypeConverter))]
public enum MyEnum
{
EnumVal1 = 0,
EnumVal2 = 1,
EnumVal3 = 2,
}
我已经实现了LocalizedEnumTypeConverter来执行此任务。
I have implemented LocalizedEnumTypeConverter to perform this task.
当我尝试使用在另一个程序集中定义的枚举使用相同的方法时出现问题,该程序集无法访问LocalizedEnumTypeConverter,并且与其他应用程序共享(也就是说,我不能添加对定义LocalizedEnumTypeConverter的程序集的引用。
The problem arises when I try to use the same approach with an enum that is defined in another assembly, that has no access to LocalizedEnumTypeConverter, and it is shared with other applications (that is, I cannot add a reference to the assembly where LocalizedEnumTypeConverter is defined).
有没有办法在运行时添加TypeConverter属性?这样我可以把枚举放在没有TypeConverter属性的其他程序集中,然后在运行时将其添加到应用程序中。
Is there a way to add the TypeConverter attribute in runtime? This way I can leave the enum in the other assembly without the TypeConverter attribute, and then add it in runtime in my application.
推荐答案
这可以使用TypeDescriptor类 https://msdn.microsoft .COM / EN-US /库/ system.componentmodel.typedescriptor.aspx 。参考下面的例子。
This can be done using TypeDescriptor class https://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx. Refer the below sample.
Attribute[] newAttributes = new Attribute[1];
newAttributes[0] = new TypeConverterAttribute(typeof(LocalizedEnumTypeConverter));
TypeDescriptor.AddAttributes(MyEnum, newAttributes);
这篇关于在运行时将TypeConverter属性添加到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!