C#自定义Attribute值的获取与优化
C#自定义Attribute值的获取是开发中会经常用到的,一般我们的做法也就是用反射进行获取的,代码也不是很复杂。
1、首先有如下自定义的Attribute
[AttributeUsage(AttributeTargets.All)]
public sealed class NameAttribute : Attribute
{
private readonly string _name; public string Name
{
get { return _name; }
} public NameAttribute(string name)
{
_name = name;
}
}
2、定义一个使用NameAttribute的类
[Description("Customer Information")]
[Name("customer_info")]
public class CustomerInfo
{
[Name("name")]
public string Name { get; set; }
[Name("address")]
public string Address;
}
3、获取CustomAttributes类上的"dept"也就很简单了
private static string GetName()
{
var type = typeof(CustomAttributes); var attribute = type.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault(); if (attribute == null)
{
return null;
} return ((NameAttribute)attribute).Name;
}
以上代码就可以简单的获取,类上的Attribute的值了,但是需求往往不是这么简单的,不仅要获取类头部Attribute上的值,还要获取字段Address头部Attribute上的值。有的同学可能就觉得这还不简单呀,直接上代码
private static string GetAddress()
{
var type = typeof (CustomAttributes); var fieldInfo = type.GetField("Address");
if (fieldInfo == null)
{
return null;
} var attribute = fieldInfo.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault(); if (attribute == null)
{
return null;
} return ((NameAttribute) attribute).Name;
}
上面代码就是获取Address字段头部上的Attribute值了。虽然我们是获取到了我们想要的,但是我们发现这样做是不是太累了,如果又扩展一个自定义的Attribute,或者又在一个新的属性或字段上标上Attribute时,我们又要写一段代码来实现我想要的,这些严重代码违反了DRY的设计原则。我们知道获取Attribute是通过反射来取的,Attribute那个值又是不变的,这样就没必要每次都要进行反射来获取了。基于以上两点代码进行了如下的优化,优化后的代码如下:
using System;
using System.Collections.Concurrent;
using System.Reflection; public static class CustomAttributeExtensions
{
/// <summary>
/// Cache Data
/// </summary>
private static readonly ConcurrentDictionary<string, object> Cache = new ConcurrentDictionary<string, object>(); /// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="TAttribute">Attribute的子类型</typeparam>
/// <typeparam name="TReturn">TReturn的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static TReturn GetCustomAttributeValue<TAttribute, TReturn>(this Type sourceType, Func<TAttribute, TReturn> attributeValueAction)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, null);
} /// <summary>
/// 获取CustomAttribute Value
/// </summary>
/// <typeparam name="TAttribute">Attribute的子类型</typeparam>
/// <typeparam name="TReturn">TReturn的子类型</typeparam>
/// <param name="sourceType">头部标有CustomAttribute类的类型</param>
/// <param name="attributeValueAction">取Attribute具体哪个属性值的匿名函数</param>
/// <param name="propertyName">field name或property name</param>
/// <returns>返回Attribute的值,没有则返回null</returns>
public static TReturn GetCustomAttributeValue<TAttribute, TReturn>(this Type sourceType, Func<TAttribute, TReturn> attributeValueAction, string propertyName)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, propertyName);
} #region private methods private static TReturn _getAttributeValue<TAttribute, TReturn>(Type sourceType, Func<TAttribute, TReturn> attributeFunc, string propertyName)
where TAttribute : Attribute
{
var cacheKey = BuildKey<TAttribute>(sourceType, propertyName);
var value = Cache.GetOrAdd(cacheKey, k => GetValue(sourceType, attributeFunc, propertyName));
if (value is TReturn) return (TReturn)Cache[cacheKey];
return default(TReturn);
} private static string BuildKey<TAttribute>(Type type, string propertyName) where TAttribute : Attribute
{
var attributeName = typeof(TAttribute).FullName;
if (string.IsNullOrEmpty(propertyName))
{
return type.FullName + "." + attributeName;
} return type.FullName + "." + propertyName + "." + attributeName;
} private static TReturn GetValue<TAttribute, TReturn>(this Type type, Func<TAttribute, TReturn> attributeValueAction, string name)
where TAttribute : Attribute
{
TAttribute attribute = default(TAttribute);
if (string.IsNullOrEmpty(name))
{
attribute = type.GetCustomAttribute<TAttribute>(false);
}
else
{
var propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
attribute = propertyInfo.GetCustomAttribute<TAttribute>(false);
}
else
{
var fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
attribute = fieldInfo.GetCustomAttribute<TAttribute>(false);
}
}
} return attribute == null ? default(TReturn) : attributeValueAction(attribute);
} #endregion
}
优化后的代码:
把不同的代码用泛型T,Fun<TAttribute,TReturn>来处理来减少重复的代码;
把取过的Attribute值存到一个ConcurrentDictionary中,下次再来取时,如果有则直接取ConcurrentDictionary中的值,如果没有才通过反射来取相应的Attribute值,这样大大的提高效率;
调用方法也更加的简单了,代码如下:
var customerInfoName = typeof(CustomerInfo).GetCustomAttributeValue<NameAttribute, string>(x => x.Name);
var customerAddressName = typeof(CustomerInfo).GetCustomAttributeValue<NameAttribute, string>(x => x.Name, "Address");
var customerInfoDesc = typeof(CustomerInfo).GetCustomAttributeValue<DescriptionAttribute, string>(x => x.Description); Console.WriteLine("CustomerInfo Name:" + customerInfoName);
Console.WriteLine("customerInfo >Address Name:" + customerAddressName);
Console.WriteLine("customerInfo Desc:" + customerInfoDesc);
运行结果:

如果你有什么好的或不好的意见欢迎拍砖!
谢谢大家的建议,己经更新(2019/11/21)
Code:Download
C#自定义Attribute值的获取与优化的更多相关文章
- .net c#获取自定义Attribute
前言: 在c#开发中,有时候我们需要读取 Attribute中的信息(关于Attribute , 我自己把他理解成一个可以为类,属性标记的东西,这个标记可以为你提供一些关于类,方法,属性的额外信息) ...
- 转:C#制作ORM映射学习笔记一 自定义Attribute类
之前在做unity项目时发现只能用odbc连接数据库,感觉非常的麻烦,因为之前做web开发的时候用惯了ORM映射,所以我想在unity中也用一下ORM(虽然我知道出于性能的考虑这样做事不好的,不过自己 ...
- 【MVC 笔记】MVC 自定义 Attribute 属性中的猫腻
原想在 MVC Action 上加一个自定义 Attribute 来做一些控制操作,最先的做法是在自定 Attribute 中定义一个属性来做逻辑判断,可惜事与愿违,这个属性值居然会被缓存起来,于是于 ...
- Django项目:CRM(客户关系管理系统)--14--06PerfectCRM实现King_admin注册功能获取内存优化处理
<th >{% get_app_name admin_class.model %}{{ admin_class }} </th> #kingadmin_tags.py # —— ...
- XsdGen:通过自定义Attribute与反射自动生成XSD
前言 系统之间的数据交互往往需要事先定义一些契约,在WCF中我们需要先编写XSD文件,然后通过自动代码生成工具自动生成C#对象.对于刚刚接触契约的人来说,掌握XMLSpy之类的软件之后确实比手写XML ...
- 自定义Attribute 服务端校验 客户端校验
MVC 自定义Attribute 服务端校验 客户端校验/* GitHub stylesheet for MarkdownPad (http://markdownpad.com) *//* Autho ...
- 从值栈获取List集合
-------------------siwuxie095 从值栈获取 List 集合 1.具体步骤 (1)在 Action 中向值栈放 List 集合 (2)在 JSP 页面中从值栈获取 List ...
- 使用c#特性,给方法或类打自定义标签再反射获取
给方法打自定义标签再反射获取 1.自定义特性类 using System; using System.Collections; using System.Collections.Generic; // ...
- map自定义键值类型
map自定义键值类型 改变Map的默认比较方式 https://www.cnblogs.com/zjfdlut/archive/2011/08/12/2135698.html 大家知道,STL中的ma ...
随机推荐
- await使用中的阻塞和并发
本文讨论,通过将Lambda还原成最普通的代码段,来解释上篇提出的疑问.并更正上篇中一些不太正确的写法.最后会给出无需等待Async方法返回值时,对Async方法使用await的建议,供大家参考.第一 ...
- eclipse 新建servlet
在mac下的eclipse新建servlet报错: 解决一: --------------------------------- 解决二: 在右键项目名称中,打开 Properties->jav ...
- 三分钟PJ隐藏SSID无线网络
一般来说用户可以通过路由或主机设置来隐藏无线信号的SSID网络信息,在这种情况下我们使用XP系统自带的无线信号扫描工具将看不到该无线网络的踪影,在这种情况下XP系统无线信号管理工具只能够看到将SSID ...
- JAVA构造方法,继承关系和SUPER关键字
SUPER可调用父类的构造方法,但要注意默认调用和参数调用. 同时,在继承类时,可以用SUPER调用其它非构造方法哟. class Test extends Object{ public Test() ...
- 模糊系统架构和简单实现--AForge.NET框架的使用(四)
原文:模糊系统架构和简单实现--AForge.NET框架的使用(四) 先说一下,为什么题目是简单实现,因为我实在没有弄出好的例子. 我原来用AForge.net做的项目中的模糊系统融入了神经网络和向量 ...
- SQL 从100万条记录中的到 成绩最高的记录
从100万条记录中的到 成绩最高的记录 问题分析:要从一张表中找到成绩最高的记录并不难,有很多种办法,最简单的就是利用TOP 1 select top 1 * from student order b ...
- 【HDOJ】1332 LC-Display
水题. #include <cstdio> #include <cstring> #include <cstdlib> #define MAXN 11 #defin ...
- 在什么情况下使用struct,struct与class的区别
Struct定义和使用 类是引用类型,是保存在托管堆中的.通过定义类,我们可以在数据的生存期上得到很高的灵活性,但是也会让程序的性能有一定的损失.虽然这种损失很小,但当我们只需要定义一个很小的结构时, ...
- 批量将文件转换为UTF-8无BOM格式
最近有一个项目需要迁移,要把文件全部转换成utf8格式的,本来想用python,后来听说PowerShell很是强大,就试着用了一下,果然好用啊! $list = Get-ChildItem .\ - ...
- BZOJ 3040 最短路 (堆优化dijkstra)
这题不是裸的最短路么?但是一看数据范围就傻了.点数10^6,边数10^7.这个spfa就别想了(本来spfa就是相当不靠谱的玩意),看来是要用堆优化dijkstra了.但是,平时写dijkstra时为 ...