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 ...
随机推荐
- python3中文字符编码问题
最近在进行网络爬虫时,被中文的编码问题搞得很头疼,特别是在windows环境下. 1.爬取到的中文网页内容,在解析时出现解析错误 一般情况下,我们都是用urllib中的相关函数,进行web页面的爬取, ...
- java 批量插入10万条数据
for (int i = 0; i < 100000; i++) { dbHelper.insert("INSERT aaa(name) Values ('1')"); } ...
- .net performance
http://msdn.microsoft.com/en-us/library/ms173196.aspx http://www.zhihu.com/question/20314377 http:// ...
- delphi线程的创建、挂起、激活与终止(用绘图做实验,简单又好用)
unit Unit1; interface usesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ...
- Linux下的QQ折腾记
用Linux最重要是要把QQ装好了,webqq很不好用.qq for linux是古董,Linux还是悲惨,很多软件有windows版本,有mac版本,就是不出linux版本.只好用wine来 ...
- 2015.9.11模拟赛 codevs4162 bzoj1774【无双大王】
题目描述 Description 无双大王hzwer扫清六合,席卷八荒,万姓倾心,四方仰德. hzwer拥有一片领土,其中有n个城市和m条双向道路.他规定每个人在领土上行走都要交过路费,同时进城也要交 ...
- [置顶] 如何更改CSDN博客高亮代码皮肤的样式,使博客看起来更有范(推荐)
由于本人写博客的时候,也没有配置博客的相关属性,因此贴出来的代码块都是CSDN默认的,因此代码背景色都是白色的,如下所示: 但是本人在浏览他人博客的时候,发现有些博客的代码块看起来比较有范,整个代码库 ...
- 控制反转(IOC)/依赖注入(DI)理解
个人学习笔记,来自Acode. 1.术语 控制反转/反向控制,英文全称“Inversion of Control”,简称IoC. 依赖注入,英文全称“Dependency Injection”,简称D ...
- Problem with generating association inside dbml file for LINQ to SQL
Question: I have created a dbml file in my project, and then dragged two tables from a database into ...
- [置顶] Win8.1慎用360优化,可能导致安装驱动出现数据无效的问题。附解决方法
2013年9月30日,更新说明: 不知道是不是我禁用了其他驱动造成 今天开机后连接手机,我的电脑里没出现MTP设备 于是打开设备管理器,发现MTP,也就是我的XPERIA U出现了感叹号图标 右键更新 ...