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 ...
随机推荐
- React进阶篇(2) -- Redux
前言 如果还不知道为什么要使用Redux,说明你暂时还不需要它. 三大原则 单一数据源 整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一 ...
- List_Delete
/*Sorting from little to large use List*/ #include <stdio.h> /* printf, scanf, NULL */ #includ ...
- iOS 开发之 GCD 不同场景使用
header{font-size:1em;padding-top:1.5em;padding-bottom:1.5em} .markdown-body{overflow:hidden} .markdo ...
- Udp 网络字节序
1.网络上的数据是一个字节一个字节的串行传递的. 2.字节序,规定,在内存里存储时,低字节在前称为小端,高字节在前称为大端,(现在主流系统都是小端的) 3.网络字节序,如果先传高字节,则是大端传输:如 ...
- [国家集训队]部落战争 最大流 BZOJ2150
题目描述 lanzerb的部落在A国的上部,他们不满天寒地冻的环境,于是准备向A国的下部征战来获得更大的领土. A国是一个M*N的矩阵,其中某些地方是城镇,某些地方是高山深涧无人居住.lanzerb把 ...
- python怎样在一行中捕获多个异常
所属网站分类: python基础 > 异常处理 作者:浮沉 链接:http://www.pythonheidong.com/blog/article/71/ 来源:python黑洞网,专注pyt ...
- Qt 学习之路 2(42):QListWidget、QTreeWidget 和 QTableWidget
Qt 学习之路 2(42):QListWidget.QTreeWidget 和 QTableWidget 豆子 2013年2月5日 Qt 学习之路 2 38条评论 上一章我们了解了 model/vie ...
- angular-ui-select 下拉框支持过滤单选多选解决方案(系列一)
angular-ui-select 官方文档:github地址:https://github.com/angular-ui/ui-select 请大家多看文档 首先注意版本的问题,如果版本不 ...
- 一些英文表达-youtube
culinary tradition 烹饪传统 crunchy 松脆的 boutique 精品店 migraine 偏头痛 colon 冒号 towel 毛巾 ecstatic 狂喜的 bok ...
- HDU - 3033 滚动数组有坑
每层至少一个,滚动时要判上一层非法与否,所以每次都要memset #include<bits/stdc++.h> #define rep(i,j,k) for(int i=j;i<= ...