常常有这样的需求:方法接受一个对象参数,要验证对象的所有字段的值是否合乎要求,如进行非空检测,长度检测等等。

比如,有这样一个Stu的类

   public class Stu
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public byte[] FileBytes { get; set; }

    }

new 一个 对象 作为参数进行传递

        static void Main(string[] args)
        {
            Stu student = new Stu()
            {
                Age = 45,
                FileBytes = new Byte[1024 * 10000]
            };

//……要在这里检测student对象的各个属性值是否合法……
Console.ReadKey(); }

怎么来判断student的合法性呢?检测student的Name字段是否有值,检测FileBytes字段是否超出指定长度

1、Required 非空检测

引用System.ComponentModel.DataAnnotations,在Stu类的Name字段上加上[Required]属性标签

2、自定义属性检测

检测FileBytes的长度,需要自定义来实现

定义一个ByteArrayMaxSizeCheckAttribute自定义属性类,继承自ValidationAttribute,如下

 public class ByteArrayMaxSizeCheckAttribute : ValidationAttribute
    {
        /// <summary>
        /// 最大大小
        /// </summary>
        private int maxsize;
        public ByteArrayMaxSizeCheckAttribute()
        {

        }
        public ByteArrayMaxSizeCheckAttribute(int size)
        {
            maxsize = size;
        }
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            var content = value as byte[];
            double filesize = content.Length / 1024 * 1.0;
            filesize = filesize / 1024 * 1.0;
            if (filesize > maxsize)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

然后,同样,在Stu类的FileBytes字段上加上两个标签

        [Required]
        [ByteArrayMaxSizeCheck(1, ErrorMessage = "{0}大小超出最大限制")]

 

Stu就应该是下面的样子

   public class Stu
    {
        [Required]
        public string Name { get; set; }
        public int Age { get; set; }
       
        [Required]
        [ByteArrayMaxSizeCheck(1, ErrorMessage = "{0}大小超出最大限制")]
        public byte[] FileBytes { get; set; }

    }
3、编写扩展方法,实现验证逻辑
 public static class ValidExtension
    {
        public static string ErrorMsg<T>(this T model) where T : class, new()
        {
            var propertis = model.GetType().GetProperties();
            string errorMsg = "";
            foreach (var info in propertis)
            {
                var attributes = info.GetCustomAttributes();
                foreach (var attribute in attributes)
                {
                    if (attribute is ValidationAttribute)
                    {
                        var reqattr = attribute as RequiredAttribute;
                        var maxsizeattr = attribute as ByteArrayMaxSizeCheckAttribute;
                        if (reqattr != null)
                        {
                            var obj = info.GetValue(model);
                            if (!reqattr.IsValid(obj))
                            {
                                errorMsg = errorMsg + reqattr.FormatErrorMessage(info.Name);
                            }
                        }
                        if (maxsizeattr != null)
                        {
                            var obj = info.GetValue(model);
                            if (!maxsizeattr.IsValid(obj))
                            {
                                errorMsg = errorMsg + maxsizeattr.FormatErrorMessage(info.Name);
                            }
                        }
                    }
                }
            }
            return errorMsg;
        }
    }

 

下面来看怎么调用验证
        static void Main(string[] args)
        {
            Stu student = new Stu()
            {
                Age = 45,
                FileBytes = new Byte[1024 * 10000]
            };
            var errorMessage = student.ErrorMsg();
            Console.WriteLine(errorMessage);
            Console.ReadKey();
        }

posted on 2017-06-15 17:27  布里渊区  阅读(1110)  评论(0编辑  收藏  举报