自定义属性

    /// <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 = ;
this.Len = ;
this.SensitiveReChar = "*";
} public SensitiveAttribute(SensitiveType type = SensitiveType.IdNumber,int start = ,int len = ,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
}

类:

    /// <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 = )]
public string IdCard { get; set; }
}

获取属性

    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() == )
{
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 = ; i < sensitiveAttr.Len - ; 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; }
}
    /// <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 = ; i < sensitiveAttr.Len - ; 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 = ; i < sensitiveAttr.Len - ; 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 = ;
private static string SYMBOL = "*"; public static String toConceal(String value)
{
if (null == value || "".Equals(value))
{
return value;
}
int len = value.Length;
int pamaone = len / ;
int pamatwo = pamaone - ;
int pamathree = len % ;
StringBuilder stringBuilder = new StringBuilder();
if (len <= )
{
if (pamathree == )
{
return SYMBOL;
}
stringBuilder.Append(SYMBOL);
stringBuilder.Append(value.Substring(len - ,));
}
else
{
if (pamatwo <= )
{
stringBuilder.Append(value.Substring(, ));
stringBuilder.Append(SYMBOL);
stringBuilder.Append(value.Substring(len - , )); }
else if (pamatwo >= SIZE / && SIZE + != len)
{
int pamafive = (len - SIZE) / ;
stringBuilder.Append(value.Substring(, pamafive));
for (int i = ; i < SIZE; i++)
{
stringBuilder.Append(SYMBOL);
}
if ((pamathree == && SIZE / == ) || (pamathree != && SIZE % != ))
{
stringBuilder.Append(value.Substring(len - pamafive));
}
else
{
stringBuilder.Append(value.Substring(len - (pamafive + )));
}
}
else
{
int pamafour = len - ;
stringBuilder.Append(value.Substring(, ));
for (int i = ; i < pamafour; i++)
{
stringBuilder.Append(SYMBOL);
}
stringBuilder.Append(value.Substring(len - ));
}
}
return stringBuilder.ToString(); } }

自定义过滤器:

    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 = ; i < sensitiveAttr.Len - ; 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 = ; i < sensitiveAttr.Len - ; 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);
}
}
        /// <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 = ; i < sensitiveAttr.Len - ; i++)
{
strSenChar += sensitiveAttr.SensitiveReChar;
}
itemValue = itemValue.ToString().Substring(, 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 = ; i < sensitiveAttr.Len - ; i++)
{
strSenChar += sensitiveAttr.SensitiveReChar;
}
itemValue = itemValue.ToString().Substring(, 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));
} }
}
}

获取属性

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

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

方法二、通过类获取

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

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

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

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();

C# 自定义属性Attribute的更多相关文章

  1. Ahjesus获取自定义属性Attribute或属性的名称

    1:设置自己的自定义属性 public class NameAttribute:Attribute { private string _description; public NameAttribut ...

  2. 自定义属性Attribute的运用

    有时候需要一个枚举类,能够承载更多的信息,于是可以利用attribute这个特性. 首先编写自己业务需求类 [AttributeUsage(AttributeTargets.Field)] publi ...

  3. JS DOM属性,包括固有属性和自定义属性,以及属性获取、移除和设置

    属性分为固有属性property和自定义属性attribute 固有属性查看 固有属性可以通过ele.property 来获取,自定义属性不行 <!DOCTYPE html> <ht ...

  4. C# VS JAVA 差异 (未完待续)

    1. 静态构造函数 C#中有静态构造函数, Java中没有静态构造函数.其实Java中有一个类似静态构造函数的东东,称作静态初始化,或者静态代码块,可以通过这样的代码实现相同的功能: 但是Java中静 ...

  5. 【学】SoapExtension 学习

    http://msdn.microsoft.com/zh-cn/library/System.Web.Services.Protocols.SoapExtension_methods(v=vs.80) ...

  6. 序列化和反序列化的几种方式(JavaScriptSerializer 、XmlSerializer、DataContractSerializer)(一)

    JavaScriptSerializer 类 为启用 AJAX 的应用程序提供序列化和反序列化功能. 命名空间:   System.Web.Script.Serialization 程序集:  Sys ...

  7. Servlet概念框架

    以 Servlet 3.0 源代码为基础.Servlet 是 Javaweb 应用的基础框架,犹如孙子兵法之于作战指挥官,不可不知. 概念框架 机制: 事件 Event, 监听器 Listener 数 ...

  8. jQuery从入门到忘记

    jQuery 是一套Javascript脚本库,注意 jQuery 是脚本库,而不是脚本框架."库"不等于"框架".jQuery 并不能帮助我们解决脚本的引用管 ...

  9. jQuery 基础语法

    jQuery介绍 1.jQuery是一个轻量级的.兼容多浏览器的JavaScript库. 2.jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方便地进行Aja ...

随机推荐

  1. [转]解读Unity中的CG编写Shader系列1——初识CG

    CG=C for Graphics  用于计算机图形编程的C语言超集 前提知识点: 1.CG代码必须用 CGPROGRAM ... ENDCG括起来 2.顶点着色器与片段着色器的主函数名称可随意,但需 ...

  2. 多线程《七》信号量,Event,定时器

    一 信号量 信号量也是一把锁,可以指定信号量为5,对比互斥锁同一时间只能有一个任务抢到锁去执行,信号量同一时间可以有5个任务拿到锁去执行,如果说互斥锁是合租房屋的人去抢一个厕所,那么信号量就相当于一群 ...

  3. 842. Split Array into Fibonacci Sequence

    Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like ...

  4. OOP2(虚函数/抽象基类/访问控制与继承)

    通常情况下,如果我们不适用某个函数,则无需为该函数提供定义.但我们必须为每个虚函数都提供定义而不管它是否被用到了,这因为连编译器也无法确定到底会适用哪个虚函数 对虚函数的调用可能在运行时才被解析: 当 ...

  5. Python3之subprocess模块

    一.简介 subprocess最早在2.4版本引入.用来生成子进程,并可以通过管道连接他们的输入/输出/错误,以及获得他们的返回值. # subprocess用来替换多个旧模块和函数 os.syste ...

  6. 数据结构54:平衡二叉树(AVL树)

    上一节介绍如何使用二叉排序树实现动态查找表,本节介绍另外一种实现方式——平衡二叉树. 平衡二叉树,又称为 AVL 树.实际上就是遵循以下两个特点的二叉树: 每棵子树中的左子树和右子树的深度差不能超过 ...

  7. IOS中NSUserDefaults的用法

    NSUserDefaults适合存储轻量级本地数据,比如要保存用户登陆的用户名.密码,使用NSUserDefaults是首选.下次再登陆的时候就可以直接从NSUserDefaults里面读取上次登陆的 ...

  8. [BJOI2012]连连看 BZOJ2661 费用流

    题目描述 凡是考智商的题里面总会有这么一种消除游戏.不过现在面对的这关连连看可不是QQ游戏里那种考眼力的游戏.我们的规则是,给出一个闭区间[a,b]中的全部整数,如果其中某两个数x,y(设x>y ...

  9. C++_代码重用5-类模板

    如果两种类只是数据类型不同,而其他代码是相同的,与其编写新的类声明,不如编写一种泛型(独立于类型的)栈.然后将具体的类型作为参数传递给这个类.这样就可以使用通用的代码生成存储不同类型值的栈. 可以使用 ...

  10. Magic Odd Square (思维+构造)

    Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both ma ...