我可以提供帮助进行翻译。以下是需要翻译的内容:
这里是一个使用它的简单属性:
在我上面的情况下,类型转换器工作得很好。它为我进行了转换。
然而,这比我的理想解决方案更复杂。如果我将类型转换器放在枚举本身上(取消上面的代码的注释),并注释掉属性上的类型转换器,则不再调用类型转换器!
我已经在其他类上使用了这种约定,而且它也很好地工作。
为什么直接在枚举上放置类型转换器不起作用?
供参考,这是我的类型转换器:
我有一个场景:我有一个枚举,并希望将其绑定并显示在 DataGridView(数据绑定)中的 DataGridViewTextBoxColumn 上。
这是我的枚举:
//[TypeConverter(typeof(EnumStringConverter))]
public enum YesNoNA
{
[EnumDescription("Yes")]
Yes,
[EnumDescription("No")]
No,
[EnumDescription("N/A")]
NA
}
这里是一个使用它的简单属性:
[TypeConverter(typeof(EnumStringConverter))]
public YesNoNA HighLimitWithinBounds { get; protected set; }
在我上面的情况下,类型转换器工作得很好。它为我进行了转换。
然而,这比我的理想解决方案更复杂。如果我将类型转换器放在枚举本身上(取消上面的代码的注释),并注释掉属性上的类型转换器,则不再调用类型转换器!
我已经在其他类上使用了这种约定,而且它也很好地工作。
为什么直接在枚举上放置类型转换器不起作用?
供参考,这是我的类型转换器:
public class EnumStringConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType)
{
if (value != null && destinationType == typeof(string))
{
return "Edited to protect the innocent!";
}
return TypeDescriptor.GetConverter(typeof(Enum)).ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
};