C#特性Attribute

1 特性说明

/// 特性:中括号声明
///
/// 就是一个类直接/间接继承Attribute
///
/// 一般以Attribute结尾,声明时可以省略掉Attribute
///
/// 错觉:每一个特性都可以带来对应的功能
/// 实际上特性添加后,编译器会在元素内部产生IL,但无法直接使用,而且metadata里面会有记录
///
/// 任何一个生效的特性,都是主动去使用的
///
/// 特性:本身是没有用的
/// 程序运行过程中能够找到这些特性,
/// 没有破坏类的封装下,可以添加额外的信息和行为

2 特性的使用

2.1 特性Attribute修饰的类

 // [Obsolete("请不要使用这个了,应该使用哪个", false)]//影响编译器运行
    [Custom(123, Description = "1234", m_Remark = "3242")]//方法不行 实际上实例化对象
    class Person
    {
        [Custom(1, Description = "ID property", m_Remark = "属性")]
        public int ID { get; set; }
        [Length(1,3)]
        public string Name { get; set; }


        [Long(111,10000000000)]
        public long QQ { get; set; }

        [Custom]
        public void Study()
        {
            Console.WriteLine($"这里是{this.Name}");
        }
        [Custom()]//方法加特性
        [return:Custom()]//返回值加特性
        public string Ansewer([CustomAttribute]string name)//给形参加特性
        {
            return $"This is {name}";
        }
    }

2.2 特性类的封装

 //AttributeTargets 指定修饰什么元素  AllowMultiple是否可重复修饰  默认:false   Inherited:是否可继承下去 默认:true
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false,Inherited = true)]//允许重复修饰
    public class CustomAttribute:Attribute
    {
        public CustomAttribute() { }
        public CustomAttribute(int n) { }
        public string Description { get; set; }
        public string m_Remark = null;
        public void Show() { }
    }

public static class ValidateExtension
    {
        public static bool Validate(this object oObject)
        {
            Type type = oObject.GetType();
             foreach (var item in type.GetProperties())
            {
                if (item.IsDefined(typeof(AbstractValidateAttribute),true))
                {
                    object[] objectAttributArray = item.GetCustomAttributes(typeof(AbstractValidateAttribute), true);
                    foreach (var attribute in objectAttributArray)
                    {
                        AbstractValidateAttribute abstractValidateAttribute = (AbstractValidateAttribute)attribute;
                        if (!abstractValidateAttribute.Validate(item.GetValue(oObject)))
                        {
                            return false;
                        }
                    }
                    
                }

                
            }
            return true;
         }
    }

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public abstract class AbstractValidateAttribute: Attribute
    {
        public abstract  bool Validate(object value);
    }

    public class LongAttribute: AbstractValidateAttribute
    {
        private long _Min = 0;
        private long _Max = 0;

        public LongAttribute(long min, long max)
        {
            this._Min = min;
            this._Max = max;
        }

        public override bool Validate(object value)
        {
            long longResult = 0;
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return false;
            }
            if (!long.TryParse(value.ToString(), out longResult))
            {
                return false;
            }
            if (longResult < this._Min || longResult > this._Max)
            {
                return false;
            }

            return true;
        }
    }

    public class LengthAttribute: AbstractValidateAttribute
    {
        private int _Min = 0;
        private int _Max = 0;

        public LengthAttribute(int min,int max)
        {
            this._Min = min;
            this._Max = max;
        }
        public override bool Validate(object value)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return false;
            }
            int nLength = value.ToString().Length;
            if (nLength < this._Min || nLength > _Max)
            {
                return false;
            }

            return true;
        }
    }




  /// <summary>
    /// 用户状态
    /// </summary>
    public enum UserState
    {
        [RemarkAttribute("正常")]
        Normal=0,//正常
        [RemarkAttribute("冻结")]
        Frozen,//冻结
        [RemarkAttribute("已删除")]
        Deleted//已删除
    }

    public class RemarkAttribute:Attribute
    {
        private string _Remark = null;
        public RemarkAttribute(string strRemark)
        {
            this._Remark = strRemark;
        }
        public string getRemark()
        {
            return this._Remark;
        }

    }

    public static class RemarkExtension
    {
        public static string GetRemark(this Enum value)//this 关键字代表扩展方法 静态类的  静态的方法 this关键字
        {
            Type type = value.GetType();
            FieldInfo fieldInfo =  type.GetField(value.ToString());
            if (fieldInfo.IsDefined(typeof(RemarkAttribute),true))
            {
                RemarkAttribute remarkAttribute  = (RemarkAttribute)fieldInfo.GetCustomAttribute(typeof(RemarkAttribute), true);
                return remarkAttribute.getRemark();
            }
            else
            {
                return value.ToString();
            }
        }
    }

 public static void Show(Person person)
        {
            //获取类上
            Type type = typeof(Person);//等价 person.GetType()
            //访问特性
            if (type.IsDefined(typeof(CustomAttribute),true))
            {
                //通过反射,创建对象
                CustomAttribute customAttribute = (CustomAttribute)type.GetCustomAttribute(typeof(CustomAttribute), true);
                
                Console.WriteLine($"{customAttribute.Description}_{customAttribute.m_Remark}");
                customAttribute.Show();
            }

            //获取Property
            Console.WriteLine("获取Property");
            PropertyInfo propertyInfo =  type.GetProperty("ID");
            if (propertyInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute customAttribute = (CustomAttribute)propertyInfo.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{customAttribute.Description}_{customAttribute.m_Remark}");
                customAttribute.Show();
            }
            //获取方法
            Console.WriteLine("获取方法");
            MethodInfo methodInfo =   type.GetMethod("Ansewer");
            if (methodInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute customAttribute = (CustomAttribute)methodInfo.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{customAttribute.Description}_{customAttribute.m_Remark}");
                customAttribute.Show();
            }

            //获取参数列表
            ParameterInfo parameterInfo  =  methodInfo.GetParameters()[0];
            if (parameterInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute customAttribute = (CustomAttribute)parameterInfo.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{customAttribute.Description}_{customAttribute.m_Remark}");
                customAttribute.Show();
            }
            //获取方法返回值
            ParameterInfo parameterInfoReturn = methodInfo.ReturnParameter;
            if (parameterInfoReturn.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute customAttribute = (CustomAttribute)parameterInfoReturn.GetCustomAttribute(typeof(CustomAttribute), true);
                Console.WriteLine($"{customAttribute.Description}_{customAttribute.m_Remark}");
                customAttribute.Show();
            }
            if(person.Validate())
            {
                Console.WriteLine("正确");
            }
            else
            {
                Console.WriteLine("错误");
            }
            
            person.Study();

            string strResult = person.Ansewer("Mario");
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值