数据验证(自定义特性)

这几天在了解ef,看了几天云里雾里(我太菜了),但在vs2010中使用ef时我觉得有些东西还是很有意思的。自己便想到分装一个逻辑层的数据验证类

1.自定义特性

  [AttributeUsage(AttributeTargets.Property)]
    public class CheckAttributes:Attribute
    {
        // 摘要:
        //     初始化类的新实例。
        public CheckAttributes(bool iskey, bool isnull)
        {
            this.EntityKeyProperty = iskey;
            this.IsNullable = isnull;
        }

        // 摘要:
        //     获取或设置一个值,该值指示属性是否为实体键的一部分。
        //
        // 返回结果:
        //     一个值,该值指示属性是否为实体键的一部分。
        public bool EntityKeyProperty { get; set; }
        //
        // 摘要:
        //     获取或设置一个值,该值指示属性是否可以具有 null 值。
        //
        // 返回结果:
        //     一个值,该值指示属性是否可以具有 null 值。
        public bool IsNullable { get; set; }
    }
View Code

2.创建带有自定义特性的实体类

 public class Ent
    {
        public static Ent Create_Ent(Int32 id, String contex)
        {
            Ent ent=new Ent();
            ent.Id = id;
            ent.Contex = contex;
            return ent;
        }

        private Int32 _id;
        [CheckAttributes(true,false)]  //是实体键,不可为空
        [DataMember]
        public Int32 Id
        {
            get { return _id; }
            set { this._id = value; }
        }

        private String _contex;
        [CheckAttributes(false,false)]  // 不是实体键,不可为空
        [DataMember]
        public String Contex
        {
            get { return _contex; }
            set { this._contex = value; }
        }
    }
View Code

3.创建验证工具类

 public class CheckData
    {
        public static bool Check(object obj)
        {
            var type = obj.GetType();
            PropertyInfo[] propertyInfos = type.GetProperties();
            bool isOk = true;
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                CheckAttributes dAttributes1 = Attribute.GetCustomAttribute(propertyInfo, typeof(CheckAttributes)) as CheckAttributes;
                object ob = propertyInfo.GetValue(obj, null);
                //检验规则
                if (dAttributes1 != null && !dAttributes1.IsNullable)
                {
                    if (ob == null)
                    {
                        isOk = false;
                        break;
                    }
                  
                }
            }
            return isOk;
        }
    }
View Code

4.测试

 static void Main(string[] args)
        {
            Ent ent = Ent.Create_Ent(1, "10");
            Console.WriteLine(CheckData.Check(ent));

            Ent ent1 = new Ent();
            Console.WriteLine(CheckData.Check(ent1));

            Ent ent2 = new Ent();
            ent2.Id = 2;
            Console.WriteLine(CheckData.Check(ent2));

            Ent ent3 = new Ent();
            ent3.Contex = "kkkk";
            Console.WriteLine(CheckData.Check(ent3));

            Console.ReadKey();
        }
View Code

结果:

True
False
False
True
原文地址:https://www.cnblogs.com/kurt/p/4582571.html