c# 特性基础

特点: 特性典型的AOP编程思想,可以在不破坏封装的前提下,动态增加功能,额外信息, 是一个类,可以标记在别的元素上面,标记后对编译/运行其实都没有影响,只是生成了一些内部的元素,普通的方式找不到但可以通过反射来获取并使用

 

特性对于程序来说一切都是假象,程序编写中无法访问到,对程序也没影响,我们通过反编译发现,特性被编译成内部元素,但是代码无法访问到,而是在matadata中记录 而反射可以动态读取并使用meatada,基于反射,就可以在程序中去识别并使用特性


对于一个字段或类上需要多个属性的,我们应该采用面向切面编程的思想来写特性的结构,采用继承的关系,这样我们可以更方便的操作; 对于不是多个判断的我们不需要采用继承的结构,一般解析特性需要:

  1. 获取类型 Type type = eValue.GetType();
  2. 获取我们需要的字段或属性... foreach (var item in type.GetProperties())
  3. 判断是否存在此特性 if (item.IsDefined(typeof(AbstractValidateAttribute), true))
  4. 找到上面的特  多个(var attributeArray = item.GetCustomAttributes(typeof(AbstractValidateAttribute), true);foreach (AbstractValidateAttribute item1 in attributeArray) )单个( RemarkAttribute remarkAttribute =(RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute));)

如果我们想要自定义特性都要继承自Attribute类

简单示例代码如下:

 [AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
    public class RemarkAttribute : Attribute
    {
        private string _Remark;
        public RemarkAttribute(string remark)
        {
            _Remark = remark;
        }
        public string Remark { get { return _Remark; } }
    }

    public static class RemarkExtend
    {
        public static string GetRemark(this Enum eValue)
        {
            try
            {
                Type type = eValue.GetType();
                FieldInfo field = type.GetField(eValue.ToString());
                RemarkAttribute remarkAttribute = (RemarkAttribute)field.GetCustomAttribute(typeof(RemarkAttribute));
                if (remarkAttribute == null)
                {
                    return field.ToString();
                }
                else
                    return remarkAttribute.Remark;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
    }
    public enum UserState
    {
        /// <summary>
        /// 正常
        /// </summary>
        [Remark("正常")]
        Normal = 0,
        /// <summary>
        /// 冻结
        /// </summary>
        [Remark("冻结")]
        Frozen = 1,
        /// <summary>
        /// 删除
        /// </summary>
        [Remark("删除")]
        Delete = 2
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值