博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 自定义属性Attribute
阅读量:4620 次
发布时间:2019-06-09

本文共 20315 字,大约阅读时间需要 67 分钟。

自定义属性

///     /// 脱敏属性    ///     public class SensitiveAttribute:Attribute    {        #region Fields        public SensitiveType SensitiveType { get; set; }        ///         /// 开始位置        ///         public int Start { get; set; }        ///         /// 长度        ///         public int Len { get; set; }        ///         /// 敏感字符替换        ///         public string SensitiveReChar { get; set; }        #endregion        #region Constructors and Destructors        public SensitiveAttribute()        {            this.Start = 1;            this.Len = 2;            this.SensitiveReChar = "*";        }        public SensitiveAttribute(SensitiveType type = SensitiveType.IdNumber,int start = 1,int len = 5,string sensitiveReChar = "*")        {            this.SensitiveType = type;            this.Start = start;            this.Len = len;            this.SensitiveReChar = sensitiveReChar;        }        #endregion        #region Public Methods and Operators        #endregion    }    ///     /// 类型    ///     public enum SensitiveType    {        IdNumber,        Name    }
View Code

类:

///     ///     ///     public class UserInfo    {        public string Code { get; set; }        public string Name { get; set; }        [Sensitive]        public string Phone { get; set; }        [Sensitive(SensitiveType.Name,Len = 3)]        public string IdCard { get; set; }    }
View Code

获取属性

public static class CustomAttributeHelper    {        #region MyRegion        /////         ///// Cache Data        /////         //private static readonly Dictionary
Cache = new Dictionary
(); /////
///// 获取CustomAttribute Value ///// /////
Attribute的子类型
/////
头部标有CustomAttribute类的类型 /////
取Attribute具体哪个属性值的匿名函数 /////
返回Attribute的值,没有则返回null
//public static string GetCustomAttributeValue
(this Type sourceType, Func
attributeValueAction) where T : Attribute //{ // return GetAttributeValue(sourceType, attributeValueAction, null); //} /////
///// 获取CustomAttribute Value ///// /////
Attribute的子类型
/////
头部标有CustomAttribute类的类型 /////
取Attribute具体哪个属性值的匿名函数 /////
field name或property name /////
返回Attribute的值,没有则返回null
//public static string GetCustomAttributeValue
(this Type sourceType, Func
attributeValueAction, // string name) where T : Attribute //{ // return GetAttributeValue(sourceType, attributeValueAction, name); //} //private static string GetAttributeValue
(Type sourceType, Func
attributeValueAction, // string name) where T : Attribute //{ // var key = BuildKey(sourceType, name); // if (!Cache.ContainsKey(key)) // { // CacheAttributeValue(sourceType, attributeValueAction, name); // } // return Cache[key]; //} /////
///// 缓存Attribute Value ///// //private static void CacheAttributeValue
(Type type, // Func
attributeValueAction, string name) //{ // var key = BuildKey(type, name); // var value = GetValue(type, attributeValueAction, name); // lock (key + "_attributeValueLockKey") // { // if (!Cache.ContainsKey(key)) // { // Cache[key] = value; // } // } //} //private static string GetValue
(Type type, // Func
attributeValueAction, string name) //{ // object attribute = null; // if (string.IsNullOrEmpty(name)) // { // attribute = // type.GetCustomAttributes(typeof(T), false).FirstOrDefault(); // } // else // { // var propertyInfo = type.GetProperty(name); // if (propertyInfo != null) // { // attribute = // propertyInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault(); // } // var fieldInfo = type.GetField(name); // if (fieldInfo != null) // { // attribute = fieldInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault(); // } // } // return attribute == null ? null : attributeValueAction((T)attribute); //} /////
///// 缓存Collection Name Key ///// //private static string BuildKey(Type type, string name) //{ // if (string.IsNullOrEmpty(name)) // { // return type.FullName; // } // return type.FullName + "." + name; //} #endregion public static List
GetSensitiveResult
(List
source) where T : class { PropertyInfo[] pro = (typeof(T)).GetProperties(); if (pro.Count() == 0) { return source; } SensitiveAttribute sensitive = new SensitiveAttribute(); var customProper = (typeof(T)).GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any()); foreach (var sou in source) { foreach (var item in customProper) { var itemValue = item.GetValue(sou, null); if (null!= itemValue) { var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true); var sensitiveAttr = (attrName as SensitiveAttribute); string strSenChar = sensitiveAttr.SensitiveReChar; for (int i = 0; i < sensitiveAttr.Len - 1; i++) { strSenChar += sensitiveAttr.SensitiveReChar; } item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null); } } //foreach (var item in pro) //{ // var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true); // var attrValue = sou.GetType().GetProperty(item.Name); // if (attrName != null) // { // var itemValue = item.GetValue(sou,null); // if (itemValue != null) // { // //item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(3, 6), "******"), null); // } // } //} } return source; } }
View Code

 

///     /// 自定义属性    ///     public static class CustomAttributeHelper    {        public static List
GetSensitiveResult
(List
source) where T : class { var customProper = (typeof(T)).GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any()); if (!customProper.Any()) { return source; } SensitiveAttribute sensitive = new SensitiveAttribute(); foreach (var sou in source) { foreach (var item in customProper) { var itemValue = item.GetValue(sou, null); if (null!= itemValue) { var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true); var sensitiveAttr = (attrName as SensitiveAttribute); string strSenChar = sensitiveAttr.SensitiveReChar; for (int i = 0; i < sensitiveAttr.Len - 1; i++) { strSenChar += sensitiveAttr.SensitiveReChar; } item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null); } } } return source; } ///
/// 脱敏属性结果 /// ///
///
///
public static T GetSensitiveResult
(T source) where T : class { var customProper = (typeof(T)).GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any()); if (!customProper.Any()) { return source; } SensitiveAttribute sensitive = new SensitiveAttribute(); foreach (var item in customProper) { var itemValue = item.GetValue(source, null); if (null != itemValue) { var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true); var sensitiveAttr = (attrName as SensitiveAttribute); string strSenChar = sensitiveAttr.SensitiveReChar; for (int i = 0; i < sensitiveAttr.Len - 1; i++) { strSenChar += sensitiveAttr.SensitiveReChar; } item.SetValue(source, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null); } } return source; } private static int SIZE = 6; private static string SYMBOL = "*"; public static String toConceal(String value) { if (null == value || "".Equals(value)) { return value; } int len = value.Length; int pamaone = len / 2; int pamatwo = pamaone - 1; int pamathree = len % 2; StringBuilder stringBuilder = new StringBuilder(); if (len <= 2) { if (pamathree == 1) { return SYMBOL; } stringBuilder.Append(SYMBOL); stringBuilder.Append(value.Substring(len - 1,1)); } else { if (pamatwo <= 0) { stringBuilder.Append(value.Substring(0, 1)); stringBuilder.Append(SYMBOL); stringBuilder.Append(value.Substring(len - 1, 1)); } else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) { int pamafive = (len - SIZE) / 2; stringBuilder.Append(value.Substring(0, pamafive)); for (int i = 0; i < SIZE; i++) { stringBuilder.Append(SYMBOL); } if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) { stringBuilder.Append(value.Substring(len - pamafive)); } else { stringBuilder.Append(value.Substring(len - (pamafive + 1))); } } else { int pamafour = len - 2; stringBuilder.Append(value.Substring(0, 1)); for (int i = 0; i < pamafour; i++) { stringBuilder.Append(SYMBOL); } stringBuilder.Append(value.Substring(len - 1)); } } return stringBuilder.ToString(); } }
View Code

自定义过滤器:

public class SensitiveCustomAttribute:ActionFilterAttribute    {                //&& (objectContent.Value.GetType().BaseType == typeof(Parm) || objectContent.Value.GetType() == typeof(Parm))        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)        {            var objectContent = actionExecutedContext.Response.Content as ObjectContent;            if (objectContent != null && objectContent.Value != null)            {                var res = objectContent.Value.GetType().GetProperty("Data");                if (null!= res)                {                    var resVal =  res.GetValue(objectContent.Value, null);                    if (resVal.GetType().IsGenericType)                    {                        foreach (var sou in (IEnumerable)resVal)                        {                            var customProper = sou.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                            foreach (var item in customProper)                            {                                var itemValue = item.GetValue(sou, null);                                if (null != itemValue)                                {                                    var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);                                    var sensitiveAttr = (attrName as SensitiveAttribute);                                    string strSenChar = sensitiveAttr.SensitiveReChar;                                    for (int i = 0; i < sensitiveAttr.Len - 1; i++)                                    {                                        strSenChar += sensitiveAttr.SensitiveReChar;                                    }                                    item.SetValue(sou, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);                                }                            }                        }                    }                    else if(resVal.GetType().IsClass)                    {                        var customProper = resVal.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                        foreach (var item in customProper)                        {                            var itemValue = item.GetValue(resVal, null);                            if (null != itemValue)                            {                                var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);                                var sensitiveAttr = (attrName as SensitiveAttribute);                                string strSenChar = sensitiveAttr.SensitiveReChar;                                for (int i = 0; i < sensitiveAttr.Len - 1; i++)                                {                                    strSenChar += sensitiveAttr.SensitiveReChar;                                }                                item.SetValue(resVal, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);                            }                        }                    }                    //var customProper3 = s.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                    //var customProper2 = objectContent.Value.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                    //var customProper = res.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                    //if (!customProper.Any())                    //{                    //    return ;                    //}                    //SensitiveAttribute sensitive = new SensitiveAttribute();                                        //foreach (var item in customProper)                    //{                    //    var itemValue = item.GetValue(res, null);                    //    if (null != itemValue)                    //    {                    //        var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);                    //        var sensitiveAttr = (attrName as SensitiveAttribute);                    //        string strSenChar = sensitiveAttr.SensitiveReChar;                    //        for (int i = 0; i < sensitiveAttr.Len - 1; i++)                    //        {                    //            strSenChar += sensitiveAttr.SensitiveReChar;                    //        }                    //        item.SetValue(res, itemValue.ToString().Replace(itemValue.ToString().Substring(sensitiveAttr.Start, sensitiveAttr.Len), strSenChar), null);                    //    }                    //}                }            }            base.OnActionExecuted(actionExecutedContext);           }    }
View Code

 

///         /// 数据脱敏        ///         ///         private void GetCustom(object resVal)        {            if (null == resVal)            {                return;            }            if (resVal.GetType().IsGenericType)            {                foreach (var sou in (IEnumerable)resVal)                {                    var customProper = sou.GetType().GetProperties().Where(p => p.CanWrite && p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                    if (!customProper.Any())                    {                        break;                    }                    foreach (var item in customProper)                    {                        if (item.PropertyType == typeof(String) || item.PropertyType == typeof(Int32) || item.PropertyType == typeof(Decimal))                        {                            var itemValue = item.GetValue(sou, null);                            if (null != itemValue)                            {                                var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);                                var sensitiveAttr = (attrName as SensitiveAttribute);                                string strSenChar = sensitiveAttr.SensitiveReChar;                                for (int i = 0; i < sensitiveAttr.Len - 1; i++)                                {                                    strSenChar += sensitiveAttr.SensitiveReChar;                                }                                itemValue = itemValue.ToString().Substring(0, sensitiveAttr.Start) + strSenChar + itemValue.ToString().Substring(sensitiveAttr.Start + sensitiveAttr.Len);                                item.SetValue(sou, itemValue, null);                            }                        }                        else                        {                            GetCustom(item);                        }                    }                }            }            else if (resVal.GetType().IsClass)            {                var customProper = resVal.GetType().GetProperties().ToList().Where(p => p.CanWrite && p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                foreach (var item in customProper)                {                    var itProp = item.PropertyType.GetProperties().ToList().Where(p => p.GetCustomAttributes(typeof(SensitiveAttribute), true).Any());                    if (item.PropertyType == typeof(String)|| item.PropertyType == typeof(Int32) || item.PropertyType == typeof(Decimal))                    {                        var itemValue = item.GetValue(resVal, null);                        if (null != itemValue)                        {                            var attrName = item.GetCustomAttribute(typeof(SensitiveAttribute), true);                            var sensitiveAttr = (attrName as SensitiveAttribute);                            string strSenChar = sensitiveAttr.SensitiveReChar;                            for (int i = 0; i < sensitiveAttr.Len - 1; i++)                            {                                strSenChar += sensitiveAttr.SensitiveReChar;                            }                            itemValue = itemValue.ToString().Substring(0, sensitiveAttr.Start) + strSenChar + itemValue.ToString().Substring(sensitiveAttr.Start + sensitiveAttr.Len);                            item.SetValue(resVal, itemValue.ToString(), null);                        }                    }                    else if (item.PropertyType.IsGenericType ||(item.PropertyType.IsClass && itProp.Any()))                    {                        GetCustom(item.GetValue(resVal, null));                    }                }            }        }
View Code

 

 

 

获取属性

方法一、定义一个类的对象获取

Person p = new Person();foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()){    Console.WriteLine(info.Name);}
View Code

方法二、通过类获取

Person p = new Person();foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()){    Console.WriteLine(info.Name);}
View Code

3、通过属性名获取属性值

p.Name = "张三";var name = p.GetType().GetProperty("Name").GetValue(p, null);Console.WriteLine(name);
View Code

4、完整代码及结果显示

var properties = typeof(Person).GetProperties();foreach (System.Reflection.PropertyInfo info in properties){   Console.WriteLine(info.Name);}Console.WriteLine("另一种遍历属性的方法:"); Person p = new Person();foreach (System.Reflection.PropertyInfo info in p.GetType().GetProperties()){   Console.WriteLine(info.Name);}             Console.WriteLine("通过属性值获取属性:"); p.Name = "张三";var name = p.GetType().GetProperty("Name").GetValue(p, null);Console.WriteLine(name);Console.ReadLine();
View Code

 

转载于:https://www.cnblogs.com/love201314/p/9435659.html

你可能感兴趣的文章
各地IT薪资待遇讨论
查看>>
splay入门
查看>>
带CookieContainer进行post
查看>>
C语言学习笔记--字符串
查看>>
关于七牛进行图片添加文字水印操作小计
查看>>
DataSource数据库的使用
查看>>
Luogu4069 SDOI2016 游戏 树链剖分、李超线段树
查看>>
Java的内部类真的那么难以理解?
查看>>
一文搞懂Java环境,轻松实现Hello World!
查看>>
hash实现锚点平滑滚动定位
查看>>
也谈智能手机游戏开发中的分辨率自适应问题
查看>>
关于 IOS 发布的点点滴滴记录(一)
查看>>
《EMCAScript6入门》读书笔记——14.Promise对象
查看>>
CSS——水平/垂直居中
查看>>
Eclipse连接mysql数据库jdbc下载(图文)
查看>>
Python中Selenium的使用方法
查看>>
三月23日测试Fiddler
查看>>
20171013_数据库新环境后期操作
查看>>
poj 1654 && poj 1675
查看>>
运维派 企业面试题1 监控MySQL主从同步是否异常
查看>>