利用反射,设置获取自定义特性

1、建立类库及实体类UseInfo.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Entities.Attributes;
 7 
 8 namespace Entities
 9 {
10     public class UserInfo:BaseModel
11     {
12         [Column(mapName:"UserName")]
13         public string Name { get; set; }
14         [Column(minLength: 6, maxLength: 12, errorMess:"no pass",regx:"")]
15         public string Pass { get; set; }
16         [Format("yyyy-MM-dd")]
17         public DateTime AddDateTime { get; set; }
18         public bool Enable { get; set; }
19 
20         [Format("F2")]
21         public decimal Total { get; set; }
22 
23         [Column(minLength:0,maxLength:1)]
24         public int Status { get; set; }
25     }
26 }

2、建立特性类

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Diagnostics;
  4 using System.Linq;
  5 using System.Reflection;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 
  9 namespace Entities.Attributes
 10 {
 11 
 12     [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
 13     public class ColumnAttribute:Attribute
 14     {
 15         public int? MinLength { get; private set; }
 16 
 17         public int? MaxLength { get; private set; }
 18 
 19         public string ErrorMess { get; private set; }
 20 
 21         public string MapName { get; private set; }
 22 
 23         public string Regx { get; private set; }
 24 
 25         public ColumnAttribute(string mapName, int minLength=0, int maxLength=0, string errorMess=null, string regx=null)
 26         {
 27             MinLength = minLength;
 28             MaxLength = maxLength;
 29             MapName = mapName;
 30             ErrorMess = errorMess;
 31             Regx = regx;
 32         }
 33 
 34         public ColumnAttribute(string mapName)
 35         {
 36             MapName = mapName;
 37         }
 38 
 39         public ColumnAttribute(string mapName, int minLength = 0)
 40         {
 41             MinLength = minLength;
 42             MapName = mapName;
 43         }
 44 
 45         public ColumnAttribute(string mapName, int minLength = 0, int maxLength = 0)
 46         {
 47             MinLength = minLength;
 48             MaxLength = maxLength;
 49             MapName = mapName;
 50         }
 51 
 52         public ColumnAttribute(string mapName, int minLength = 0, int maxLength = 0, string errorMess = null)
 53         {
 54             MinLength = minLength;
 55             MaxLength = maxLength;
 56             MapName = mapName;
 57             ErrorMess = errorMess;
 58         }
 59 
 60         public ColumnAttribute( int minLength = 0, int maxLength = 0, string errorMess = null, string regx = null)
 61         {
 62             MinLength = minLength;
 63             MaxLength = maxLength;
 64             ErrorMess = errorMess;
 65             Regx = regx;
 66         }
 67     }
 68 
 69     public static class ColumnEx
 70     {
 71         public static string GetName(this PropertyInfo property)
 72         {
 73             if (property.IsDefined(typeof(ColumnAttribute), true))
 74             {
 75                 var attr = Attribute.GetCustomAttribute(property, typeof(ColumnAttribute), false);
 76                 return (attr as ColumnAttribute).MapName??property.Name;
 77             }
 78             else
 79             {
 80                 return property.Name;
 81             }
 82         }
 83 
 84         //public override string ToString()
 85         //{
 86         //    if (this.GetType().IsDefined(typeof(ColumnAttribute), false))
 87         //    {
 88         //        Attribute attr = Attribute.GetCustomAttribute(this.GetType(), typeof(ColumnAttribute), false);
 89         //        if (attr != null)
 90         //        {
 91         //            return string.Format("{0} likes to eat {1}.", ((ColumnAttribute)attr).MapName,
 92         //                ((ColumnAttribute)attr).MapName);
 93         //        }
 94         //    }
 95         //    return base.ToString();
 96         //}
 97 
 98         public static bool IsVerify<T>(T model) where T : class
 99         {
100             var type = model.GetType();
101             var properties = type.GetProperties();
102 
103             foreach (var propertyInfo in properties)
104             {
105                 var val = propertyInfo.GetValue(model,null);
106                 var Strval = val?.ToString();
107                 var attr = Attribute.GetCustomAttribute(propertyInfo, typeof(ColumnAttribute), false) as ColumnAttribute;
108                 if (attr != null)
109                 {
110                     if (attr.MinLength > 0)
111                     {
112                         #region MinLength
113 
114                         if (!string.IsNullOrWhiteSpace(Strval) && Strval.Length >= attr.MinLength)
115                         {
116                             Debug.WriteLine(
117                                 $"Info:{type.Name}--{propertyInfo.Name}--Value MinLength {attr.MinLength}√");
118                         }
119                         else
120                         {
121                             Debug.WriteLine(
122                                 $"Error:{type.Name}--{propertyInfo.Name}--Value MinLength {attr.MinLength}");
123                             return false;
124                         }
125 
126                         #endregion
127                     }
128 
129                     if (attr.MaxLength > 0)
130                     {
131                         #region MaxLength
132                         if (!string.IsNullOrWhiteSpace(Strval) && Strval.Length <= attr.MaxLength)
133                         {
134                             Debug.WriteLine(
135                                 $"Info:{type.Name}--{propertyInfo.Name}--Value MaxLength {attr.MaxLength}√");
136                         }
137                         else
138                         {
139                             Debug.WriteLine(
140                                 $"Error:{type.Name}--{propertyInfo.Name}--Value MaxLength {attr.MaxLength}");
141                             return false;
142                         }
143                         #endregion
144                     }
145                 }
146             }
147 
148             return false;
149         }
150     }
151 
152 
153 }

AttributeUsage:修饰此特性使用范围

IsVerify:集成自定义数据验证

Format:特性与Column特性写法基本差不多,作用是格式化输出

自定义特性必须集成,Attribute类,类名称以“Attribute”结尾

3、调用测试

 1  [TestMethod]
 2         public void TestDataVerify()
 3         {
 4             var user=new UserInfo();
 5             user.Pass = "123156";
 6             user.Status = 3;
 7 
 8             if (ColumnEx.IsVerify(user))
 9             {
10 
11             }
12         }
13 
14         [TestMethod]
15         public void TestFormatOut()
16         {
17             var user = new UserInfo();
18             user.Pass = "123156";
19             user.Status = 3;
20             user.Total = (decimal)3.556878;
21             user.AddDateTime=DateTime.Now;
22             var plist = user.GetType().GetProperties();
23             foreach (var item in plist)
24             {
25                 Console.WriteLine(item.GetName());
26                 Debug.WriteLine(item.FormatOutput(item.GetValue(user,null)));
27             }
28         }

 

posted @ 2019-01-01 14:27  qishidz  阅读(100)  评论(0编辑  收藏  举报