C# characteristics (Attribute) learning summary 2

Provide examples of additional behaviors through features: custom features for data validation (validate the size and non-empty of the attribute value)

There is an attribute of QQ in the student class. The effective QQ cannot be less than 100000 (5 digits), and cannot be greater than 999999999999 (12 digits), and the QQ attribute cannot be empty. If these validations are met, it returns true, otherwise it returns false.

 

Declare an abstract class, all custom features inherit from this abstract class, in order to ensure that the custom features implement data validation methods.

    /// <summary>
    /// 抽象类 基类
    /// </summary>
    public abstract class AbstractVaildDataAttribute : Attribute
    {
        /// <summary>
        /// 验证数据是否符合要求
        /// </summary>
        /// <param name="oValue"></param>
        /// <returns></returns>
        public abstract bool ValidData(object oValue);
    }

 

Declare the characteristics of non-empty validation attributes:

    /// <summary>
    /// 声明一个可以对属性应用 空字符串效验的特性
    /// 效验值是否为空
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class RequireAttribute : AbstractVaildDataAttribute
    {
        public override bool ValidData(object oValue)
        {
            return !string.IsNullOrEmpty(oValue.ToString());
        }
    }

 

Declare the characteristics of the validation attribute value size:

    /// <summary>
    /// 声明一个可以对属性应用LongAttribute的特性
    /// 效验值的范围
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class LongAttribute : AbstractVaildDataAttribute
    {
        private long _Min = 0;
        private long _Max = 0;

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

        public override bool ValidData(object oValue)
        {
            long lValue = 0;
            return oValue != null && long.TryParse(oValue.ToString(), out lValue) && lValue >= _Min && lValue <= _Max;
        }
    }

 

 Declare a student class and add two custom features ('Long','Require') above the attributes:

 public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [Long(10000, 999999999999)]
        [Require]
        public long QQ { get; set; }

    }

 

Declare an extension method to call reflection to verify the value of the property:

        /// <summary>
        /// 效验属性的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool ValidDataExtend<T>(this T t) {
            Type type = t.GetType();
            foreach (var prop in type.GetProperties())
            {
                if (prop.IsDefined(typeof(AbstractVaildDataAttribute),true))
                {
                    object oValue = prop.GetValue(t);//获取要校验类型的值
                    object[] oAttributeArr = prop.GetCustomAttributes(typeof(AbstractVaildDataAttribute), true);//获取所有自定义的特性
                    foreach (AbstractVaildDataAttribute attr in oAttributeArr)
                    {
                        if (!attr.ValidData(oValue))
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

 

Call the extension method to verify the effect of the feature:

      static void Main(string[] args)
        {
            Student student = new Student()
            {
                Id = 1,
                Name = "张三",
                QQ = 1234565555
            };

            if (student.ValidDataExtend())
            {
                Console.WriteLine("效验通过");
            }
            else
            {
                Console.WriteLine("效验不通过");
            }

            Console.ReadKey();
        }

 Results of the:

 

Overall realization idea:

1. Declare the abstract class (base class)

2. Declare non-empty verification characteristics and numerical value verification characteristics 

3. Apply features to attributes

4. Use the reflective access feature to verify whether the value meets the requirements

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/112792035