OK,接着就轮到本文的第二个主角——EnumDescriptionAttribute了。
只需要如下使用EnumDescriptionAttribute标注Value1和Value2就行:
public enum SimpleStatus { [NBear.Common.EnumDescription(DefaultDescription="Desc of Value1")] Value1 = 1, [NBear.Common.EnumDescription(DefaultDescription="Desc of Value2")] Value2 = 2 }
OK,不需要任何额外设置了,再运行上面的页面,您将能看到DropDownList中显示的文字是我们指定的自定义信息了。很酷不是吗?
再等一秒钟,我们还是不会满足的,虽然我们可以指定自定义说明信息,但是,如果是多语言环境,我们需要运行时对枚举值的显示不同的文字信息,还有很多情况,我们需要从数据库中的枚举描述表读取对枚举的描述信息。
对此,我们当然也提供了解决方案。
我们只需要继承EnumDescriptionAttribute即可。下面的MyEnumDescriptionAttribute演示了一个自定义的枚举描述实现:
public class MyEnumDescriptionAttribute : NBear.Common.EnumDescriptionAttribute { private static string[] customDescs = new string[] { "custom desc of Value1", null }; //the second value is null here to use the DefaultDescription set in enum definition public override string GetDescription(object enumValue) { return customDescs[(int)enumValue] ?? base.GetDescription(enumValue); } }
这个类重载了EnumDescriptionAttribute的GetDescription()方法,从一个内存中的数组中读取描述信息。类似的,我们也可以在这里从资源文件或者数据库中读取说明信息,都只需要重载这个方法就可以了。
您一定注意到其中的注释代码了,假如,对某个枚举值,我们的自定义方法取不到自定义的描述信息,那么,它会首先查看对这个枚举值标注的MyEnumDescriptionAttribute有没有指定DefaultDescription,如果制定则返回这个内容,否则就返回枚举值的ToString()内容。
使用MyEnumDescriptionAttribute描述SimpleStatus如下:
public enum SimpleStatus { [MyEnumDescription(DefaultDescription="Default Desc of Value1")] Value1 = 1, [MyEnumDescription(DefaultDescription="Default Desc of Value2")] Value2 = 2 }
再次运行页面,您将看到,DropDownList中对应Value1显示的信息为custom desc of Value1,而对应Value2显示的信息为Default Desc of Value2。为什么呢?因为对Value1我们能取到MyEnumDescriptionAttribute返回的自定义信息,而对Value2,MyEnumDescriptionAttribute返回null,那么,默认的描述信息将被应用。是不是很神奇呢?
甚至,您可以对同一个Enum类型的不同成员项混合使用不同的EnumDescriptionAttribute或其继承类来指定描述信息(有这样的需求吗^-^)。但是,每个枚举项只有第一个EnumDescriptionAttribute或其继承类标注会生效,多余的标注会被忽略。
好了,基本介绍完了,斗胆称这个方案为完美方案,别扔臭鸡蛋就好。:)
篇后语
除了结合数据绑定控件使用EnumDescriptionAttribute之外,您也可以单独使用EnumDescriptionAttribute以透明获取的枚举值描述信息。调用EnumDescriptionAttribute.GetDescriptions(enumType)这个静态方法就可以得到指定枚举类型的所有枚举值的由EnumDescriptionAttribute或其继承类标注的描述信息。