linzy

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
/// <summary>
    /// Retrieves the name of the constant in the specified enumeration that has the specified value.
    /// </summary>
    /// <param name="t"></param>
    /// <param name="v"></param>
    /// <returns></returns>
    public static string GetEnumName(System.Type t, object v)
    {
      try
      {
        return Enum.GetName(t, v);
      }
      catch
      {
        return "Unknown";
      }
    }

    /// <summary>
    /// Get specified description of the specified enum
    /// </summary>
    /// <param name="t"></param>
    /// <param name="v"></param>
    /// <returns></returns>
    public static string GetEnumDescription(System.Type t, object v)
    {
      try
      {
        FieldInfo fi = t.GetField(GetEnumName(t, v));
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return (attributes.Length > 0) ? attributes[0].Description : GetEnumName(t, v);
      }
      catch
      {
        return "Unknown";
      }
    }

 

posted on 2014-04-24 09:36  linzy  阅读(406)  评论(0编辑  收藏  举报