关于枚举enum的tostring方法不能重写的一种替代方案
2009-05-02 17:18
357 查看
本文内容来源 http://blogs.msdn.com/abhinaba/archive/2005/10/20/483000.aspx
在.net 中,枚举的ToString 方法不能够被重写,有时候我们不想直接显示枚举的标识的时候,想已另一种方式替代显示内容,就可以采取下面介绍的这种方式来实现。
using System;
using System.Reflection;
enum Coolness : byte
{
[Description("Not so cool")]
NotSoCool = 5,
Cool, // since description same as ToString no attr are used
[Description("Very cool")]
VeryCool = NotSoCool + 7,
[Description("Super cool")]
SuperCool
}
class Description : Attribute
{
public string Text;
public Description(string text)
{
Text = text;
}
}
在.net 中,枚举的ToString 方法不能够被重写,有时候我们不想直接显示枚举的标识的时候,想已另一种方式替代显示内容,就可以采取下面介绍的这种方式来实现。
using System;
using System.Reflection;
enum Coolness : byte
{
[Description("Not so cool")]
NotSoCool = 5,
Cool, // since description same as ToString no attr are used
[Description("Very cool")]
VeryCool = NotSoCool + 7,
[Description("Super cool")]
SuperCool
}
class Description : Attribute
{
public string Text;
public Description(string text)
{
Text = text;
}
}
class Program { static string GetDescription(Enum en) { Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false); if (attrs != null && attrs.Length > 0) return ((Description)attrs[0]).Text; } return en.ToString(); } static void Main(string[] args) { Coolness coolType1 = Coolness.Cool; Coolness coolType2 = Coolness.NotSoCool; Console.WriteLine(GetDescription(coolType1)); Console.WriteLine(GetDescription(coolType2)); } }
相关文章推荐
- android开发Enum (枚举)的更轻量级的替代方案 —— @IntDef的使用
- 关于静态方法为什么不能被重写的一点思考以及overload的一些坑
- 关于toString方法的重写工具ToStringBuilder
- 关于静态方法为什么不能被重写的一点思考以及overload的一些坑。
- android开发Enum (枚举)的更轻量级的替代方案 —— @IntDef的使用 原创 2017年11月28日 09:17:58 77 最近在翻看Android源码的时候,无意中看到这么一个注解,
- 关于toString方法的重写工具ToStringBuilder
- 关于lua5.2中table.getn方法不能用的代替方案
- 关于重写toString方法
- 关于重写equals方法,hashcode方法,toString方法 ,compareto()方法
- 【原创】关于java对象需要重写equals方法,hashcode方法,toString方法 ,compareto()方法的说明
- 关于VMware虚拟机中的Ubuntu 12-04不能连接网络的一种解决方法
- 关于不能用莱布尼兹准则判别级数敛散性时的其中一种方法示例
- 关于静态方法为什么不能被重写的一点思考以及overload的一些坑。
- Java Enum枚举替代方案--Android IntDef/StringDef Annotation注解
- 关于toString方法的重写工具ToStringBuilder
- 关于C#类中重写ToString方法和PHP类中__tostring()方法的比较
- 关于enum类型的本地化的一种方法探索:
- 关于“Base 一种Acid的替代方案”
- 关于重写 toString() 方法
- 关于ModalPopupExtender控件不能居中显示的一些解决方法