C# 自定义属性Attribute

自定义属性

    /// <summary>
    /// 脱敏属性
    /// </summary>
    public class SensitiveAttribute:Attribute
    {
        #region Fields
        public SensitiveType SensitiveType { get; set; }

        /// <summary>
        /// 开始位置
        /// </summary>
        public int Start { get; set; }

        /// <summary>
        /// 长度
        /// </summary>
        public int Len { get; set; }

        /// <summary>
        /// 敏感字符替换
        /// </summary>
        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
    }

    /// <summary>
    /// 类型
    /// </summary>
    public enum SensitiveType
    {
        IdNumber,
        Name
    }
View Code

类:

    /// <summary>
    /// 
    /// </summary>
    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

        ///// <summary>
        ///// Cache Data
        ///// </summary>
        //private static readonly Dictionary<string, string> Cache = new Dictionary<string, string>();

        ///// <summary>
        ///// 获取CustomAttribute Value
        ///// </summary>
        ///// <typeparam name="T">Attribute的子类型</typeparam>
        ///// <param name="sourceType">头部标有CustomAttribute类的类型</param>
        ///// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
        ///// <returns>返回Attribute的值,没有则返回null</returns>
        //public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction) where T : Attribute
        //{
        //    return GetAttributeValue(sourceType, attributeValueAction, null);
        //}

        ///// <summary>
        ///// 获取CustomAttribute Value
        ///// </summary>
        ///// <typeparam name="T">Attribute的子类型</typeparam>
        ///// <param name="sourceType">头部标有CustomAttribute类的类型</param>
        ///// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
        ///// <param name="name">field name或property name</param>
        ///// <returns>返回Attribute的值,没有则返回null</returns>
        //public static string GetCustomAttributeValue<T>(this Type sourceType, Func<T, string> attributeValueAction,
        //    string name) where T : Attribute
        //{
        //    return GetAttributeValue(sourceType, attributeValueAction, name);
        //}

        //private static string GetAttributeValue<T>(Type sourceType, Func<T, string> attributeValueAction,
        //    string name) where T : Attribute
        //{
        //    var key = BuildKey(sourceType, name);
        //    if (!Cache.ContainsKey(key))
        //    {
        //        CacheAttributeValue(sourceType, attributeValueAction, name);
        //    }

        //    return Cache[key];
        //}

        ///// <summary>
        ///// 缓存Attribute Value
        ///// </summary>
        //private static void CacheAttributeValue<T>(Type type,
        //    Func<T, string> 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<T>(Type type,
        //    Func<T, string> 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);
        //}

        ///// <summary>
        ///// 缓存Collection Name Key
        ///// </summary>
        //private static string BuildKey(Type type, string name)
        //{
        //    if (string.IsNullOrEmpty(name))
        //    {
        //        return type.FullName;
        //    }

        //    return type.FullName + "." + name;
        //}

        #endregion

        public static List<T> GetSensitiveResult<T>(List<T> 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

 

    /// <summary>
    /// 自定义属性
    /// </summary>
    public static class CustomAttributeHelper
    {
        public static List<T> GetSensitiveResult<T>(List<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 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;
        }
            
        /// <summary>
        /// 脱敏属性结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T GetSensitiveResult<T>(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

 

        /// <summary>
        /// 数据脱敏
        /// </summary>
        /// <param name="resVal"></param>
        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

 

posted @ 2018-08-07 10:48  bxzjzg  阅读(2900)  评论(0编辑  收藏  举报