欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

通过特性(attribute)为枚举添加更多信息示例

程序员文章站 2024-02-25 18:25:39
特性(attribute)是将额外数据关联到一个属性(以及其他构造)的一种方式,而枚举则是在编程中最常用的一种构造,枚举本质上其实是一些常量值,相对于直接使用这些常量值,枚...

特性(attribute)是将额外数据关联到一个属性(以及其他构造)的一种方式,而枚举则是在编程中最常用的一种构造,枚举本质上其实是一些常量值,相对于直接使用这些常量值,枚举为我们提供了更好的可读性。我们知道枚举的基础类型只能是值类型(byte、sbyte、short、ushort、int、uint、long 或 ulong),一般的情况下枚举能够满足我们的需求,但是有时候我们需要为枚举附加更多信息,仅仅只是使用这些值类型是不够的,这时通过对枚举类型应用特性可以使枚举带有更多的信息。

在枚举中使用descriptionattribute特性

首先引入:using system.componentmodel 命名空间,下面是一个枚举应用了descriptionattribute特性:

复制代码 代码如下:

enum fruit
{
    [description("苹果")]
    apple,
    [description("橙子")]
    orange,
    [description("西瓜")]
    watermelon
}

下面是一个获取description特性的扩展方法:

复制代码 代码如下:

/// <summary>
/// 获取枚举描述特性值
/// </summary>
/// <typeparam name="tenum"></typeparam>
/// <param name="enumerationvalue">枚举值</param>
/// <returns>枚举值的描述/returns>
public static string getdescription<tenum>(this tenum enumerationvalue)
   where tenum : struct, icomparable, iformattable, iconvertible
{
   type type = enumerationvalue.gettype();
   if (!type.isenum)
   {
  throw new argumentexception("enumerationvalue必须是一个枚举值", "enumerationvalue");
   }

   //使用反射获取该枚举的成员信息
   memberinfo[] memberinfo = type.getmember(enumerationvalue.tostring());
   if (memberinfo != null && memberinfo.length > 0)
   {
  object[] attrs = memberinfo[0].getcustomattributes(typeof(descriptionattribute), false);

  if (attrs != null && attrs.length > 0)
  {
 //返回枚举值得描述信息
 return ((descriptionattribute)attrs[0]).description;
  }
   }
   //如果没有描述特性的值,返回该枚举值得字符串形式
   return enumerationvalue.tostring();
}

最后,我们就可以利用该扩展方法获取该枚举值得描述信息了:

复制代码 代码如下:

public static void main(string[] args)
{
//description = "橙子"
string description = fruit.orange.getdescription();
}