zoukankan      html  css  js  c++  java
  • 反射(2)

    反射例子——获取枚举的备注信息

    static void Main(string[] args)
    {
    var str = ColorType.Blue.GetRemark();

    Console.WriteLine(str);
    Console.ReadLine();
    }

    public static string GetRemark(this Enum em)
    {
    Type type = em.GetType();
    FieldInfo fieldInfo = type.GetField(em.ToString());
    if (fieldInfo == null)
    {
    return string.Empty;
    }
    object[] attrs = fieldInfo.GetCustomAttributes(typeof(RemarkAttribute), false);
    string name = string.Empty;
    foreach (RemarkAttribute attr in attrs)
    {
    name = attr.Remark;
    }
    return name;
    }

    public class RemarkAttribute : Attribute
    {
    public RemarkAttribute(string remark)
    {
    this.Remark = remark;
    }

    public string Remark { get; set; }
    }

    public enum ColorType
    {
    [Remark("黑色")] Black = 1,

    [Remark("蓝色")] Blue = 2,

    [Remark("红色")] Red = 3
    }

    结果:蓝色

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

             

  • 相关阅读:
    (五)Ajax修改购物车单品数量
    (四)加入购物车和购物车操作
    flask blueprint
    2.1.2 BCD码
    2.1.1进位计数制
    1.2.3 计算机系统的层次结构
    flask的宏 macro
    计算机组成原理习题
    flask模版继承和include
    flask自定义过滤器
  • 原文地址:https://www.cnblogs.com/xiao-wo-niu/p/11597441.html
Copyright © 2011-2022 走看看