首页 > 代码库 > Attribute小试

Attribute小试

  项目需要导入Excel,需要对内容进行效验,但是效验的方式都很简单,主要是判断非空字段和应为数字的字段是否为数字。 因为判断的方式大致相同,逐个字段去判断实在太费劲了,所以想到Attribute,可以用这个来实现。

  首先是Attribute类

  

public class CheckAttribute : Attribute
    {
        /// <summary>
        /// 必填级别 1 必填 2 选填 3为后续设计保留字段
        /// </summary>
        public int NeedType { get; set; }

        /// <summary>
        /// 限制类型 0 为 字符串 1为int
        /// </summary>
        public int ContentType { get; set; }
  }

  然后再类中加上对应的特性,其中Name为必填的字符串 Age为必填的Int Addr为非填的字符串

 class TestClass
    {
        [Check(NeedType = 1, ContentType = 0)]
        public string Name { get; set; }

        [Check(NeedType = 1, ContentType = 1)]
        public int Age  { get; set; }

        [Check(NeedType = 2, ContentType = 0)]
        public string Addr { get; set; }
    }

  然后再是验证类

 public class ValidationModel
    {
        public bool Validate(object obj)
        {
            var t = obj.GetType();

            var properties = t.GetProperties();
            foreach (var property in properties)
            {
                if (!property.IsDefined(typeof(CheckAttribute), false)) continue;

                var attributes = property.GetCustomAttributes(typeof(CheckAttribute), false);
                foreach (var attribute in attributes)
                {
                    var needType = (int)attribute.GetType().
                        GetProperty("NeedType").
                        GetValue(attribute);

                    var contentType = (int)attribute.GetType().
                        GetProperty("ContentType").
                        GetValue(attribute);
                    var propertyValue = http://www.mamicode.com/property.GetValue(obj) as string;>

  在这种类似的有大量相似验证的地方,用Attribute的方式比挨个字段去比较的方式省了很多重复代码,代码可读性也更高

Attribute小试