C# 特性Attribute实例 运用反射获取特性,枚举反射

特性类似于代码注释,但特性能从程序中通过反射获取,注释是获取不到的


建一个类People.cs
里面创建2个属性
 public class People
    {
        public int Id { get; set; }
        public string name { get; set; }

    }
然后建立一个特性类CustomerAttribute.cs
/// <summary>
    /// 特性就是一个类,继承Attribute即可
    /// 通常以Attribute结尾
    /// </summary>
    public class CustomerAttribute:Attribute
    {
        private string Name = "";
        private int Vision = 1;
        public CustomerAttribute(string name, int vision)
        {
            this.Name = name;
            this.Vision = vision;
        }
        public void show()
        {
            Console.WriteLine("作者是{0},系统版本号为{1}",this.Name,this.Vision);
        }
    }

再将People.cs类前面加上特性
[Customer("Eleven",2)]//特性Customer
     public class People
    {
        public int Id { get; set; }
        public string name { get; set; }

    }
这样我们在控制台应用程序里面运用反射就可获取到People类上面的特性
 Type type = typeof(People);

 object[] attrubuteArray = type.GetCustomAttributes(typeof(CustomerAttribute), true);

 if (attrubuteArray != null && attrubuteArray.Length>0)
 {
         ((CustomerAttribute)attrubuteArray[0]).show();

  }
最终显示: ,就获取到People的特性值了


同样的也可以通过反射获取枚举的特性

 public static class RemarkExtention
    {
        public static string GetRemark(this Enum enumValue)
        {
            //通过反射  获取对象
            //找到RemarkAttribute
            //绕后调用GetDescrition对象
            //返回提示
            FieldInfo type = enumValue.GetType().GetField(enumValue.ToString());
            object[] attrubuteArray = type.GetCustomAttributes(typeof(RemarkAttribute), true);
            if (attrubuteArray != null && attrubuteArray.Length > 0)
            {
                return ((RemarkAttribute)attrubuteArray[0]).GetDescription();

            }
            else
            {
                return enumValue.ToString();
            }
        }
    }
    public class RemarkAttribute : Attribute
    {
        private string Description = "";
        public RemarkAttribute(string description)
        {
            this.Description = description;
        }
        public string GetDescription()
        {
            return this.Description;
        }
    }
    public enum UserState
    {
        /// <summary>
        /// 正常状态
        /// </summary>
        [Remark("正常状态")]
        Normal = 0,
        /// <summary>
        /// 冻结状态
        /// </summary>
        [Remark("冻结状态")]
        Frozen = 1,
        /// <summary>
        /// 删除状态
        /// </summary>
        [Remark("删除状态")]
        Deleted = 2

    }

控制台中调用: Console.WriteLine(UserState.Deleted.GetRemark());  输出的为删除状态

源码链接:https://pan.baidu.com/s/1MpoLMGdbYOEPVSdZHMcA_g 密码:utqf


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值