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 = ;
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的更多相关文章
- Ahjesus获取自定义属性Attribute或属性的名称
1:设置自己的自定义属性 public class NameAttribute:Attribute { private string _description; public NameAttribut ...
- 自定义属性Attribute的运用
有时候需要一个枚举类,能够承载更多的信息,于是可以利用attribute这个特性. 首先编写自己业务需求类 [AttributeUsage(AttributeTargets.Field)] publi ...
- JS DOM属性,包括固有属性和自定义属性,以及属性获取、移除和设置
属性分为固有属性property和自定义属性attribute 固有属性查看 固有属性可以通过ele.property 来获取,自定义属性不行 <!DOCTYPE html> <ht ...
- C# VS JAVA 差异 (未完待续)
1. 静态构造函数 C#中有静态构造函数, Java中没有静态构造函数.其实Java中有一个类似静态构造函数的东东,称作静态初始化,或者静态代码块,可以通过这样的代码实现相同的功能: 但是Java中静 ...
- 【学】SoapExtension 学习
http://msdn.microsoft.com/zh-cn/library/System.Web.Services.Protocols.SoapExtension_methods(v=vs.80) ...
- 序列化和反序列化的几种方式(JavaScriptSerializer 、XmlSerializer、DataContractSerializer)(一)
JavaScriptSerializer 类 为启用 AJAX 的应用程序提供序列化和反序列化功能. 命名空间: System.Web.Script.Serialization 程序集: Sys ...
- Servlet概念框架
以 Servlet 3.0 源代码为基础.Servlet 是 Javaweb 应用的基础框架,犹如孙子兵法之于作战指挥官,不可不知. 概念框架 机制: 事件 Event, 监听器 Listener 数 ...
- jQuery从入门到忘记
jQuery 是一套Javascript脚本库,注意 jQuery 是脚本库,而不是脚本框架."库"不等于"框架".jQuery 并不能帮助我们解决脚本的引用管 ...
- jQuery 基础语法
jQuery介绍 1.jQuery是一个轻量级的.兼容多浏览器的JavaScript库. 2.jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方便地进行Aja ...
随机推荐
- virtueBox实现虚拟机的复制和粘贴
1.在设备--共享粘贴板--勾选双向. 2.在设备--拖放--勾选双向. 3.在设备--安装增强功能,然后进入虚拟机安装增强功能即可.
- 计算机基础知识和tcp详解
计算机基础知识 作为应用软件开发程序员是写应用软件的,而应用软件必须应用在操作系统之上,调用操作系统接口,由操作系统控制硬件 比如客户端软件想要基于网络发送一条消息给服务端软件,流程是: 1.客户端软 ...
- 关于“java.lang.OutOfMemoryError : unable to create new native Thread”的报错问题
好吧 我发誓这是postgresql的Mirroring Controller的RT测试的最后一个坑了. 在这个RT测试的最后,要求测试Mirroring Controller功能在长时间运行下的稳定 ...
- 190411Python面向对象编程
一.面向对象的概念 类:把一类事物的相同特征抽取出来整合到一起就是一个类,类是一个抽象的概念 对象:基于类创建的一个具体的事物 class People(object): '这是一个人类的类' def ...
- 三个常用的PHP图表类库
Jpgraph 只要把example中的require_once路径改了就放进来用吧,我下的是最新版的jpgraph-3.5.0b1,反正测试嘛,我记得跟3.0.7还是有差别的,把文件名都重新命名过了 ...
- Flask Web开发实战(入门、进阶与原理解析)
URL重定向 错误响应 > 如果你想手动返回错误响应,可以使用Flask提供的abort()函数. XML 上下文全局变量 [](https://img2018.cnblogs.com/blog ...
- artDialog不能拖拽的问题
需要引用下面这个文件: https://github.com/aui/artDialog/edit/master/dist/dialog-plus.js
- Hibernate处理一个实体映射多张相同结构的数据表--动态映射
[转自] http://blog.csdn.net/majian_1987/article/details/8725197 LZ在项目中需要处理这样一个业务,每天都有终端设备上传GPS位置信息到服务端 ...
- SQL语句练习45题(从第11题开始)
CREATE TABLE student (sno VARCHAR(3) NOT NULL, sname VARCHAR(4) NOT NULL, ssex VARCHAR(2) NOT NULL, ...
- jQuery随笔-自定义属性获取+tooltip
1.Jquery自定义属性获取 1) 通过自定义属性值获取document console.log($('[data-id='+item_id+']',listWrap)); $('[data-id= ...